A set is an unordered collection of unique values. It automatically drops duplicates, tests membership extremely fast, and supports the mathematical set operations — union, intersection, difference. Reach for it whenever uniqueness or fast "is it in here?" matters.
Creating sets
s = {1, 2, 2, 3} # {1, 2, 3} — the duplicate 2 is droppeds.add(4) # {1, 2, 3, 4}s.discard(1) # remove 1 (no error if absent)empty = set() # NB: {} is an empty DICT, not a set!
Fast membership
Checking x in s on a set is near-instant (O(1) on average) regardless of size — far faster than scanning a list. If you repeatedly test membership, a set is the right tool:
seen = set()for item in stream:if item in seen: # O(1) checkcontinueseen.add(item)unique = set([1, 1, 2, 3]) # {1, 2, 3} — de-duplicate a listcount = len(set(words)) # number of distinct words
Set algebra
| Operator | Meaning |
|---|---|
a & b | Intersection — in both |
a | b | Union — in either |
a - b | Difference — in a, not b |
a ^ b | Symmetric difference — in one, not both |
a = {1, 2, 3}b = {2, 3, 4}a & b # {2, 3}a | b # {1, 2, 3, 4}a - b # {1}a ^ b # {1, 4}
Key takeaways
- 01Sets store unique values and are unordered — duplicates are dropped automatically.
- 02Membership testing (x in s) is very fast — O(1) average.
- 03Set algebra: & intersection, | union, - difference, ^ symmetric difference.
- 04set(list) is the idiomatic way to de-duplicate.
- 05Beware: {} is an empty dict — use set() for an empty set.
