Sets
Set Basics
Creating and using sets
Interview: Essential for deduplication and O(1) membership testing — common interview tool
Sets are unordered collections of unique, hashable elements. They provide O(1) average-case membership testing and are implemented as hash tables. Sets are ideal for deduplication, membership checking, and mathematical set operations.
Creating Sets
- Literal:
{1, 2, 3}— curly braces with elements - Empty set:
set()— NOT{}(that's an empty dict!) - From iterable:
set([1, 2, 2, 3])→{1, 2, 3}— removes duplicates - Elements must be hashable: numbers, strings, tuples — NOT lists, dicts, or sets
Key Properties
- Unordered: No guaranteed order; don't rely on iteration order
- Unique: Duplicates are automatically removed
- Mutable: Can add/remove elements (but elements themselves must be immutable)
- Hashable elements only: Can't put lists, dicts, or other sets inside a set
Performance
- Membership (in): O(1) average vs O(n) for lists — massive speedup for large collections
- Add/remove: O(1) average
- Uses more memory than lists due to hash table overhead
Common Pitfall
{} creates an empty dictionary, not an empty set. Use set() for an empty set. This is one of the most common Python gotchas.
Use Cases
Removing duplicates from collections
Fast membership testing (O(1) vs O(n) for lists)
Finding common or different elements between collections
Tracking seen/visited items in algorithms (BFS, DFS)
Common Mistakes
Using {} instead of set() for empty set ({} creates a dict)
Expecting sets to maintain insertion order (use dict.fromkeys() for ordered unique items)
Trying to add mutable elements (lists, dicts) to a set (raises TypeError)
Not knowing that set iteration order is arbitrary and can change between runs