Sets in Python
Sets are unordered collections of unique elements. They are mutable and do not allow duplicates.
Creating Sets
Python
# Empty set
empty_set = set()
# Set with elements
numbers = {1, 2, 3, 2, 4} # Duplicates are removed
Accessing Set Elements
Unlike lists and tuples, sets do not support indexing. You cannot access elements by their position. However, you can check if an element is present in a set using the in
keyword.
Python
my_set = {1, 2, 3}
print(2 in my_set) # Output: True
Set Operations
Sets support mathematical set operations:
- Union: Combines elements from both sets.Python
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1 | set2 # or set1.union(set2)
- Intersection: Returns elements present in both sets.Python
intersection_set = set1 & set2 # or set1.intersection(set2)
- Difference: Returns elements present in set1 but not in set2.Python
difference_set = set1 - set2 # or set1.difference(set2)
- Symmetric difference: Returns elements present in either set but not both.Python
symmetric_difference_set = set1 ^ set2 # or set1.symmetric_difference(set2
)
Key Points
- Sets are unordered, meaning elements have no specific position.
- Sets are mutable, meaning you can add or remove elements.
- Sets are optimized for membership testing and mathematical set operations.
How do you create an empty set?
Use set()
to create an empty set.
Are sets mutable?
Yes, sets are mutable
Can sets contain duplicate elements?
No, sets only contain unique elements.
Are sets ordered?
Sets are unordered, meaning the elements don’t have a specific position.
How do you add an element to a set?
Use the add()
method.
How do you remove an element from a set?
Use the remove()
or discard()
methods.
What is the difference between remove()
and discard()
?
remove()
raises a KeyError
if the element is not found, while discard()
does nothing.
Can I use sets for mathematical set operations?
Yes, sets support operations like union, intersection, difference, and symmetric difference.
Can I use a set as a dictionary key?
Yes, as long as the elements in the set are hashable.