Python Sets: Unordered Collections
1 min readSets in Python are collections of unique elements. They are unordered and do not allow duplicate values.
**Creating Sets**
Sets are defined using curly braces `{}` or the `set()` constructor:
numbers = {1, 2, 3, 4, 5}
unique_numbers = set([1, 2, 2, 3, 4])
**Set Operations**
Sets support operations such as union, intersection, and difference:
# Union
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
# Intersection
intersection_set = set1 & set2
# Difference
difference_set = set1 – set2
**Example**:
print(union_set) # Output: {1, 2, 3, 4, 5}
print(intersection_set) # Output: {3}
print(difference_set) # Output: {1, 2}
**Set Methods**
Sets come with methods to perform various operations:
– `add()`: Adds an element to the set.
– `remove()`: Removes an element from the set.
– `clear()`: Removes all elements from the set.
**Example**:
numbers.add(6)
numbers.remove(3)
print(numbers) # Output: {1, 2, 4, 5, 6}
**Conclusion**
Sets are useful when you need to handle collections of unique items and perform mathematical operations on them.