Sets in Python
Creating Sets
s = {1, 2, 3}
s = set([1, 2, 2, 3]) # {1, 2, 3} - removes duplicates
empty = set() # NOT {} (that's empty dict!)
Properties
- Unordered - no indexing
- Unique elements only
- Elements must be hashable
Adding/Removing
add(x)- Add single elementupdate(iterable)- Add multipleremove(x)- Remove (KeyError if missing)discard(x)- Remove (no error if missing)pop()- Remove and return arbitrary element
Set Operations
a | b # Union
a & b # Intersection
a - b # Difference
a ^ b # Symmetric difference
Comparisons
a <= bora.issubset(b)- Subseta >= bora.issuperset(b)- Superseta.isdisjoint(b)- No common elements
Frozenset
Immutable set, can be dict key:
fs = frozenset([1, 2, 3])
Key Points
{}creates dict, not set! Useset()- Elements must be hashable
remove()raises error,discard()doesn’t- Operators:
|union,&intersection,-difference