Sub topic 12
Why Sets Are Fast: Hash Tables
This chapter assumes you know how to create sets and use the in operator. It also assumes you know why set elements must be hashable. Here you will see the mechanism that makes set lookups fast, and the cases where that speed disappears.
The core idea
A list finds an element by comparing it to each item in turn. Searching a list of a million items can take a million comparisons. A set instead uses a hash table. A hash table is an array of slots. The element's hash value decides which slot to check.
A hash is an integer that hash() computes from an object. Python uses it like this:
- Call
hash(x)to get an integer. - Reduce that integer to a slot position in the table.
- Look in that slot. If it is empty,
xis not in the set. - If the slot holds an element, compare it with
xusing==. If they are equal,xis in the set.
Steps 1 to 3 do not depend on how many elements the set holds. This is why a membership test takes roughly constant time, written O(1), on average. A list needs time proportional to its length, written O(n).
Measuring the difference
import timeit
n = 100_000
as_list = list(range(n))
as_set = set(as_list)
missing = -1 # worst case for the list: it must scan every item
list_time = timeit.timeit(lambda: missing in as_list, number=200)
set_time = timeit.timeit(lambda: missing in as_set, number=200)
print(f"list: {list_time:.4f}s set: {set_time:.6f}s")
print(set_time < list_time) # TrueThe exact times depend on your machine. The set is typically thousands of times faster here, and the gap grows as n grows.
Collisions
Two different elements can map to the same slot. This is a collision. When it happens, Python probes other slots in a deterministic sequence until it finds a match or an empty slot. To keep probing short, Python resizes the table as the set grows, so it never becomes too full. A resize copies every element into a larger table. An occasional add is therefore slower than the rest. Averaged over many additions, add is still O(1).
Hash and equality must agree
The table only works if equal objects have equal hashes. Python's built-in types follow this rule:
print(hash(1) == hash(1.0)) # True, because 1 == 1.0
print(len({1, 1.0, True})) # 1, all three are equal to each otherA class you write yourself must follow the same rule. If you define __eq__, define __hash__ from the same fields:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
print(len({Point(1, 2), Point(1, 2)})) # 1If you define __eq__ without __hash__, Python sets __hash__ to None, and instances become unhashable. Mutable objects are unhashable for a related reason. If an element's hash changed after insertion, the set would look in the wrong slot and lose track of it.
Where the speed ends
Sets are fast for lookups, but they have costs.
- Memory. A hash table keeps spare empty slots, so a set uses more memory than a list with the same elements.
- Building cost. Creating a set from a list takes O(n) time. Converting a list to a set for a single lookup is slower than scanning the list once. Build the set once, then reuse it for many lookups.
- Bad hashes. If many elements share the same hash, probing gets long and lookups degrade toward O(n). Built-in types rarely cause this. A poorly written
__hash__, such as one that always returns1, will. - No position. Slots are chosen by hash, not by insertion order, so a set has no indexing and no reliable order. Iteration order can differ between runs, because string hashes are randomized per process.
| Operation | list | set |
|---|---|---|
| `x in container` | O(n) | O(1) average |
| Add one element | O(1) append | O(1) average |
| Index by position | O(1) | Not supported |
| Keeps order | Yes | No |
Exercise
A function runs if word in banned_list once for each of 50,000 words, where banned_list is a list of 10,000 strings. What change speeds it up, and why does it help?
Show answer
Convert banned_list to a set once, before the loop, with banned = set(banned_list), and test word in banned. Each lookup then hashes the word and checks one slot, which is O(1) on average, instead of scanning up to 10,000 strings. The one-time O(n) conversion cost is paid back across the 50,000 lookups.