Python Sets
uniqueness, O(1) membership, and set algebra
30 min · interactive lesson with runnable code and 7 graded exercises.
What you'll be able to do
- Create sets correctly — and avoid the {} trap
- Explain why x in a_set is O(1) on average
- Use |, &, -, ^ and subset checks fluently
- Know when to reach for frozenset
What is a set?
Unique, unordered, hashable
A set is an unordered collection of unique, hashable items. Duplicates disappear automatically:
- unique items only
- unordered — no s[0]
- mutable (set)
- membership is O(1) on average
- items must be hashable
Removing duplicates from a list — with or without keeping the order:
Adding and removing
add, update, remove vs discard
Fast membership
Why sets are powerful
A list answers x in nums by checking items one by one — O(n). A set hashes x and jumps straight to where it would live — O(1) on average. Measure it:
This is the classic interview upgrade — convert once, then look up cheaply:
Set operations
Union, intersection, difference
Sets support math-style operators. Each has a method twin (a.union(b), …). Play with them:
In-place versions modify the existing set instead of building a new one:
When to use a set
Real-world patterns
frozenset
The immutable set
frozenset is a set that can't change. Because it's immutable it's hashable — so it can be a dict key or live inside another set:
Common pitfalls
Spot the bug