Sub topic 5
Hash tables: fast lookup and membership
This chapter assumes you know Python lists and dictionaries, can read basic Big-O notation, and have seen the cost of scanning a list. It covers how hash tables work, what they make cheap, and the errors that trip people up.
The working model
A hash table stores items in an array of slots. To place a key, it computes a number from the key, called a hash. It then maps that number to a slot index. To find the key later, it repeats the same computation and jumps straight to that slot. It does not scan the other items.
Python's dict (key to value) and set (keys only) are both hash tables. Their average cost for lookup, insert and delete is O(1).
Two different keys can map to the same slot. This is a collision. The table resolves it by comparing keys and probing other slots. If many keys collide, operations slow toward O(n). With a good hash function and a table that resizes as it fills, collisions stay rare, so the average case holds.
Membership tests
The most common win is testing whether something is present. A list scans element by element. A set does one hash lookup.
names_list = ["ada", "grace", "alan"]
names_set = set(names_list)
print("grace" in names_list) # True, scans the list: O(n)
print("grace" in names_set) # True, hash lookup: O(1) on averageFor three names the difference is invisible. For a million names checked thousands of times, the list version becomes the bottleneck. Building the set costs O(n) once, so it pays off when you check membership repeatedly.
What hash tables do not give you
The O(1) speed comes from giving up order-based operations.
| Operation | Hash table | Sorted list with binary search |
|---|---|---|
| Exact lookup | O(1) average | O(log n) |
| Insert | O(1) average | O(n), shifting elements |
| Next larger value | Not supported | O(log n) |
| Range query | Scan everything | O(log n + k) |
If you need "the smallest key above 25" or "all keys between 10 and 40", a hash table is the wrong tool. Use a sorted structure, covered in a later chapter.
Keys must be hashable
A key must have a hash that never changes while it is in the table. Mutable containers such as lists can change, so Python refuses them as keys. Immutable values such as strings, numbers and tuples of immutable values work.
try:
lookup = {[1, 2]: "pair"}
except TypeError as error:
print(error) # unhashable type: 'list'
lookup = {(1, 2): "pair"}
print(lookup[(1, 2)]) # pairConvert a list to a tuple when you need a composite key, for example grid coordinates.
Common errors
- Using a list for repeated membership checks on large data. Convert to a set first.
- Using a mutable object as a key, or mutating an object after it was inserted in a set.
- Expecting sorted iteration. Since Python 3.7, a
dictiterates in insertion order, but that is not sorted order. Sets give no useful order. - Assuming O(1) is a guarantee. It is an average. Keys crafted to collide, or a poor custom
__hash__, degrade it. - Forgetting memory. Hash tables keep spare empty slots, so they use more memory than a list of the same items.
Exercise
You store 100,000 user IDs and must check, 50,000 times, whether an incoming ID is already known. You also occasionally need the smallest known ID greater than a given ID. Which structure handles the checks, and what do you do about the second need?
Show answer
Use a set for the 50,000 membership checks, since each is O(1) on average instead of O(n) for a list. A set cannot answer "next larger ID", so that query needs a sorted structure, such as a sorted list with bisect. If the second need is rare, you can keep both. Otherwise, choose a sorted structure alone, accepting O(log n) lookups.
Exercise
Why does {[1, 2]: "pair"} raise a TypeError while {(1, 2): "pair"} works, and how would you use grid coordinates as keys?
Show answer
A list is mutable, so its contents and therefore its hash could change after insertion, and the table could no longer find it. A tuple of immutable values cannot change, so it is hashable. Store coordinates as tuples such as (row, col).