Sets
Fast membership and unique items.
A set is a hash table with keys, but no values. It answers one question incredibly fast. Is this item in here? And it never holds duplicates.

- A hash table without values
- Is it in here? Instantly
- No duplicates
Set operations
Sets support the maths you may remember from school. The bar means union, everything in either set. The ampersand means intersection, only what's in both. And minus means difference, what's in the first but not the second. Run it. Priya and Jo are in both clubs.
chess = {"Priya", "Sam", "Jo"}
music = {"Jo", "Alex", "Priya", "Mia"}
print("either:", sorted(chess | music))
print("both: ", sorted(chess & music))
print("chess only:", sorted(chess - music))either: ['Alex', 'Jo', 'Mia', 'Priya', 'Sam'] both: ['Jo', 'Priya'] chess only: ['Sam']
Set costs
Adding, removing, and checking membership are all O of one on average. Union and intersection depend on the sizes of the sets. Remember, sets have no order, and they can only hold things that never change, like numbers, strings, and tuples. Not lists.
| Operation | Example | Cost |
|---|---|---|
| add / remove | s.add(x) | O(1) |
| membership | x in s | O(1) |
| union | a | b | O(len(a) + len(b)) |
| intersection | a & b | O(smaller set) |
Summary
Sets give O of one membership checks, and remove duplicates for free. Union, intersection, and difference compare groups. Next, the most famous interview question of all. Two sum.
Key takeaways- x in set is O(1)
- | & -
- No duplicates, no order