Sets
Sets
In Python, a set is an unordered collection of unique elements. Sets are similar to lists or dictionaries, but they have a unique property: they do not allow duplicate values. Additionally, sets are mutable, meaning you can modify them after creation. However, the elements of a set must be immutable.
Key features of sets:
1. Unordered:
Sets do not maintain the order of elements. When you iterate over a set, the order in which elements are retrieved may vary.
2. Unique Elements:
Sets only contain unique elements. If you try to add an element that already exists in the set, it won't be duplicated.
3. Mutable:
You can add and remove elements from a set after it's created.
Here's how you can create a set:
```python
my_set = {1, 2, 3}
```
Alternatively, you can use the `set()` function:
```python
my_set = set([1, 2, 3])
```
To access elements in a set, you cannot use indexing because sets are unordered. However, you can check for membership (if an element is in the set) using the `in` keyword.
```python
print(1 in my_set) # Output: True
print(4 in my_set) # Output: False
```
To add elements to a set, you can use the `add()` method.
```python
my_set.add(4)
```
To remove elements, you can use the `remove()` method. If the element is not present, a `KeyError` is raised. Alternatively, you can use `discard()` to remove an element without raising an error if it's not present.
```python
my_set.remove(2)
my_set.discard(3)
```
Sets are useful for various operations such as finding unique elements, performing mathematical set operations (union, intersection, difference), and removing duplicates from other collections.
```python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union of sets
union_set = set1.union(set2) # {1, 2, 3, 4, 5}
# Intersection of sets
intersection_set = set1.intersection(set2) # {3}
# Difference of sets
difference_set = set1.difference(set2) # {1, 2}
```
In summary, sets in Python are a versatile data structure for handling unique elements and performing set operations efficiently.
Comments
Post a Comment