Sub topic 12
Why sets are fast: hash tables
This chapter assumes you can create sets, use in on them, and know that set elements must be hashable. It explains the mechanism behind those facts: how a set finds an element without scanning, when that speed breaks down, and what the speed costs.
The problem a hash table solves
Checking x in some_list compares x with each item in turn until it finds a match or reaches the end. The work grows with the length of the list. A list of a million items needs up to a million comparisons for a failed lookup.
A set avoids the scan. It uses the value itself to compute where the value should be stored, then looks only at that place. The structure that does this is a hash table: an array of slots, plus a function that maps each value to a slot number.
From value to slot
The mapping function is the built-in hash(). It turns an object into an integer. A set takes that integer and reduces it to a valid position in its internal array, in CPython by masking off the low bits, which is like taking hash(x) % table_size for a power-of-two size.
print(hash(42)) # 42, small ints hash to themselves
print(hash(1) == hash(1.0) == hash(True)) # True
print(hash((1, 2)) == hash((1, 2))) # True, equal tuples hash equally
print(hash(-1)) # -2, CPython reserves -1 as an internal error codeTwo rules connect hashing to equality:
- Objects that compare equal must have the same hash.
- An object's hash must not change while it is in a set.
Rule 1 is why {1, 1.0, True} has a single element: the three values are equal and hash identically, so the set sees them as the same key. Rule 2 is why mutable containers such as lists are unhashable. If a list's contents changed after insertion, the set would look in the wrong slot and could no longer find it.
String hashes are different from integer hashes. Python randomizes them per process (controlled by PYTHONHASHSEED), so the same string can hash to a different number on each run. This also means the iteration order of a set of strings can differ between runs.
A lookup, step by step
The diagram shows what happens on x in s.
The branch on the right matters. Two different values can map to the same slot. This is called a collision. It is unavoidable: there are far more possible values than slots. A hash table is defined by how it handles collisions.
How collisions are handled
There are two common strategies.
- Chaining: each slot holds a small list of the items that landed there. A lookup scans that short list.
- Open addressing: each slot holds at most one item. If the slot is taken by a different item, the table tries another slot following a fixed probe sequence, and the lookup follows the same sequence.
CPython sets use open addressing. Each slot stores the item's hash alongside a reference to the item, so a lookup can compare the stored hash first. It calls == only when the full hashes match, which skips most unnecessary equality checks.
Chaining is easier to read, so here is a small teaching version. It is not how CPython does it, but the cost model is the same.
class ToySet:
def __init__(self, size=8):
self._buckets = [[] for _ in range(size)]
self._count = 0
def _index(self, item):
return hash(item) % len(self._buckets)
def add(self, item):
bucket = self._buckets[self._index(item)]
if item in bucket:
return
bucket.append(item)
self._count += 1
if self._count > 0.75 * len(self._buckets):
self._resize()
def __contains__(self, item):
return item in self._buckets[self._index(item)]
def __len__(self):
return self._count
def _resize(self):
items = [x for bucket in self._buckets for x in bucket]
self._buckets = [[] for _ in range(len(self._buckets) * 2)]
for x in items:
self._buckets[self._index(x)].append(x)
ts = ToySet()
for n in range(100):
ts.add(n)
print(len(ts)) # 100
print(42 in ts) # True
print(1000 in ts) # False
print(len(ts._buckets)) # 256, the table doubled as it filledEach lookup computes one index and scans one short bucket. It never touches the other items.
Load factor and resizing
A table with many items in few slots has many collisions. The ratio of items to slots is the load factor. ToySet keeps it at or below 0.75 by doubling the array and re-placing every item when it goes over. CPython also grows its set tables when they get too full, with its own thresholds.
Resizing is expensive because every item must be re-placed, since each item's slot depends on the table size. It happens rarely and the table roughly doubles each time, so the cost averaged over many insertions stays constant. This is why add is described as amortized O(1): most calls are very cheap and an occasional call is slow.
Cost summary
| Operation | Average case | Worst case | Column |
|---|---|---|---|
| `x in s`, `add`, `discard`, `remove` | O(1) | O(n) | |
| `len(s)` | O(1) | O(1) | |
| Iterating over `s` | O(n) | O(n) | |
| `a \ | b` | O(len(a) + len(b)) | O(len(a) \* len(b)) |
| `a & b` | O(min(len(a), len(b))) | O(len(a) \* len(b)) | |
| `a - b` | O(len(a)) | O(len(a) \* len(b)) | |
| `list(s)`, `set(iterable)` | O(n) | O(n²) |
"Average" assumes the hash function spreads items evenly. The worst case happens when many items collide.
Intersection is cheap because Python loops over the smaller set and probes the larger one, so a tiny set intersected with a huge one costs little.
Seeing the speed difference
Timing results depend on your machine, so this program prints only the comparison. Looking up the last element is the worst case for a list.
import timeit
n = 100_000
as_list = list(range(n))
as_set = set(as_list)
target = n - 1
t_list = timeit.timeit(lambda: target in as_list, number=200)
t_set = timeit.timeit(lambda: target in as_set, number=200)
print("set faster than list:", t_set < t_list) # True
print("speedup is large:", t_list / t_set > 100) # True on typical hardwareOn a list of 100,000 items the gap is typically several orders of magnitude. Doubling the list roughly doubles the list's lookup time and leaves the set's unchanged.
When the speed disappears
Constant-time lookup depends on a good hash function. If every object returns the same hash, every item competes for the same probe sequence and the set degrades into a linear scan.
import timeit
class BadKey:
def __init__(self, name):
self.name = name
def __hash__(self):
return 1 # every instance collides
def __eq__(self, other):
return isinstance(other, BadKey) and self.name == other.name
class GoodKey(BadKey):
def __hash__(self):
return hash(self.name)
n = 1000
bad = {BadKey(i) for i in range(n)}
good = {GoodKey(i) for i in range(n)}
t_bad = timeit.timeit(lambda: BadKey(n - 1) in bad, number=200)
t_good = timeit.timeit(lambda: GoodKey(n - 1) in good, number=200)
print(BadKey(5) in bad) # True, still correct
print(t_bad > t_good) # True, but much slowerThe bad version returns correct answers. A poor hash costs time, not correctness. Both classes keep the rule that equal objects have equal hashes, which is what correctness requires.
Breaking that rule does cause wrong answers. If two equal objects hash differently, a lookup can land in a different slot from the stored object and report that it is missing.
String hash randomization has a security purpose. Without it, an attacker who knows the hash function could send many inputs that all collide, such as keys in a web request, and force the O(n) worst case on a server. Randomizing the seed per process makes such inputs hard to craft.
What the speed costs
- Memory. A set keeps its table partly empty, and each slot stores a hash and a pointer. A set uses substantially more memory than a list of the same items.
sys.getsizeofon each shows the difference. - Build time. Creating a set from a list costs O(n) and allocates the table. If you test membership once,
x in my_listis cheaper than building a set first. Build the set when you will do many lookups. - No order, no indexing. Slot position comes from the hash, not from insertion order, so there is no
s[0]and no meaningful iteration order. - Elements must be hashable. This follows from the design. It is not an arbitrary restriction.
Edge cases worth knowing
- Deleting an item leaves a marker in its slot so that probe sequences passing through it still work. Many deletions can leave a table full of markers, and Python cleans these up when it resizes.
- Iterating over a set while adding or removing elements raises
RuntimeError: Set changed size during iteration. Iterate over a copy such aslist(s)if you need to modify the set. - A frozenset has the same lookup cost as a set. Its hash is computed from its elements, so it can be a key in another set or dict.
- Hash equality is not object equality. Two different objects can share a hash, and the set then falls back to
==. A set therefore never confuses them.
Summary
A set maps each element to a slot through hash(), so a lookup checks one place instead of every item. Collisions are resolved by probing, and the table resizes to keep collisions rare. This gives average O(1) membership, insertion and removal. The costs are extra memory, no ordering, a requirement that elements be hashable with consistent equality, and a worst case of O(n) when hashes collide.
Exercise
A set holds 1,000,000 strings. You need to test only one string for membership, then discard the set. Is it faster to build the set first or to test against the original list? Explain using the cost model.
Show answer
Testing against the list is faster. Building the set costs O(n) and allocates a large table, and the single lookup it enables saves at most one O(n) scan. The list scan costs O(n) once and builds nothing. A set pays off only when many lookups share one build cost.
Exercise
A class defines __eq__ to compare two instances by their id field, but it does not define __hash__ to match. Instances are stored in a set. What can go wrong if __hash__ returns id(self) (the object's memory address) instead of a hash based on the id field?
Show answer
Two instances with the same id field are equal but have different hashes, which breaks the rule that equal objects must hash equally. The set may place them in different slots, so it can store both as separate elements, and a lookup with a new equal instance can report that it is missing. The fix is def __hash__(self): return hash(self.id).
Exercise
Why does {1, 1.0, True} have length 1, and which part of the hash table lookup makes that happen?
Show answer
The three values are equal and have the same hash (1). The lookup lands in the same slot, finds an item with a matching hash, and the equality check succeeds, so the set treats the later values as duplicates of the first and does not add them.