Hash based data structures: set, dict, counter
Fast O(1) membership and lookup using set and dict, plus defaultdict and Counter from collections, with common CP patterns.
set
A set is an unordered collection of unique values. Duplicates are automatically discarded.
Creating a Set
Basic Operations
| Operation | Method | Complexity |
|---|---|---|
| Add | add(x) | O(1) |
| Remove | remove(x) | O(1) |
| Lookup | x in s | O(1) |
| Size | len(s) | O(1) |
Compare this to a list where x in lst is O(n). For large collections with frequent lookups, a set is dramatically faster.
Sets are Unordered
Elements have no guaranteed order — you cannot access by index:
If you need sorted unique elements, use sorted(s) when iterating:
Set Operations
Sets support mathematical set operations:
Practical Examples
Removing Duplicates from a List
If order matters, use a different approach (as shown in the lists module).