Python sets — unique collections and set operations
set creation, add, remove, discard, union, intersection, difference, symmetric difference, frozenset, membership testing
Sets
A set is an unordered collection of unique, hashable items. It automatically removes duplicates and provides fast O(1) membership testing.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
# dedup a list:
unique = set([1, 2, 2, 3, 3])
print(unique) # {1, 2, 3}
Set Operations
print(a | b) # {1,2,3,4,5,6} union
print(a & b) # {3,4} intersection
print(a - b) # {1,2} difference (in a, not b)
print(a ^ b) # {1,2,5,6} symmetric difference
Modifying Sets
a.add(10)
a.remove(1) # raises KeyError if absent
a.discard(99) # safe — no error if absent
print(3 in a) # True — fast membership test
Frozenset
A frozenset is an immutable set — it is hashable and can be used as a dictionary key. Create one with frozenset([1, 2, 3]). Sets do not support indexing or slicing because they have no defined order.
Sets shine for membership testing and deduplication. If you have a list of IDs and need to check whether a new ID already exists, converting the list to a set first and then testing membership is dramatically faster than looping. The set difference operator is useful for finding what changed between two states: new_ids - old_ids gives you added items, old_ids - new_ids gives removed ones. Remember that sets do not preserve insertion order, so if order matters, use a list with a set as a parallel lookup structure.
