Sub topic 2
Why hash tables need hash functions
This chapter assumes you can write basic Python, use the modulo operator and bitwise XOR, and know what a dictionary (a key-to-value map) does. The previous chapter defined a hash function as a deterministic map from arbitrary input to a fixed-size value. Here you will see the main job that definition serves: making lookups fast.
The problem a hash table solves
Suppose you store 1,000,000 user records and look them up by username. You have two obvious options:
- An unsorted list. A lookup scans every record, so the cost grows with the number of records, written O(n).
- A sorted list with binary search. A lookup takes O(log n) comparisons, but every insert has to keep the list sorted.
A hash table aims for lookups and inserts that take constant time on average, written O(1). It gets there by turning the key into an array position, so it can jump straight to the right spot instead of searching.
An array gives you O(1) access when you already know the index. The hash function supplies that index. It converts any key (a string, a tuple, a number) into an integer, and that integer is reduced to a valid array position.
The working model
A hash table has four parts:
- An array of buckets. A bucket is one slot that can hold zero or more entries.
- A hash function that turns a key into an integer.
- A reduction step that maps that integer onto the array, usually with
% len(buckets). - A collision strategy for when two different keys land in the same bucket.
Notice the last step. The hash only narrows the search to one bucket. The table then uses ordinary equality (==) to confirm it has the right key. The hash is a shortcut to a small candidate set. It does not prove that two keys are the same.
A working implementation
The following table uses chaining: each bucket holds a list of (key, value) pairs. It reuses the FNV-1a hash that appears later in this tutorial.
def fnv1a_32(data: bytes) -> int:
h = 0x811C9DC5 # FNV offset basis
for byte in data:
h ^= byte
h = (h * 0x01000193) & 0xFFFFFFFF # FNV prime, keep 32 bits
return h
class ChainedTable:
def __init__(self, bucket_count=8):
self.buckets = [[] for _ in range(bucket_count)]
self.size = 0
def _index(self, key: str) -> int:
return fnv1a_32(key.encode()) % len(self.buckets)
def put(self, key, value):
bucket = self.buckets[self._index(key)]
for i, (existing_key, _) in enumerate(bucket):
if existing_key == key:
bucket[i] = (key, value) # overwrite, size unchanged
return
bucket.append((key, value))
self.size += 1
def get(self, key, default=None):
for existing_key, value in self.buckets[self._index(key)]:
if existing_key == key:
return value
return default
table = ChainedTable()
for name in ["ada", "grace", "linus", "margaret", "dennis", "barbara"]:
table.put(name, len(name))
print(table.get("grace"))
print(table.get("nobody", "missing"))
print([len(b) for b in table.buckets])The last line prints how many entries each bucket holds. With six keys and eight buckets, some buckets will usually hold two entries and some will be empty. That is normal, and it is the collision handling doing its job.
Why the hash function decides the speed
The table's O(1) promise depends entirely on the hash function. Consider the cost of one lookup:
- Computing the hash costs time proportional to the key's length.
- Indexing into the array costs constant time.
- Scanning the bucket costs time proportional to the bucket's length.
If the hash spreads keys evenly, each bucket holds about n / m entries, where n is the number of entries and m is the number of buckets. This ratio is the load factor. Keep it below a small constant, and the scan is a few comparisons.
If the hash sends many keys to the same bucket, that bucket grows long and the scan costs O(n). In the worst case, every key lands in one bucket and your hash table is a linked list with extra steps.
| Hash behavior | Bucket lengths | Lookup cost |
|---|---|---|
| Even spread | About `n / m` each | O(1) on average |
| Clustered | A few long buckets, many empty | Grows with cluster size |
| Constant (every key to the same value) | One bucket holds everything | O(n) |
This is why the next chapters ask for uniformity and speed. A table is only as fast as its hash function is evenly distributed and cheap to compute.
Two contracts the hash must honor
A hash table works only if keys and their hashes obey these rules:
- Equal keys must produce equal hashes. If
a == b, thenhash(a) == hash(b). Otherwiseaandbare stored in different buckets, and a lookup for one never finds the other. - A key's hash must not change while it is in the table. The table computed the bucket once, at insert time. If the hash changes later, the entry sits in a bucket where lookups no longer look.
The reverse of rule 1 does not hold. Unequal keys may share a hash. That is a collision, and the table handles it by comparing with == inside the bucket.
How Python enforces these contracts
Python's built-in dict and set call hash() on each key and then compare with ==. Mutable containers such as lists are unhashable, because their contents (and so their hash) could change:
try:
{[1, 2]: "value"}
except TypeError as error:
print(error)
print({(1, 2): "value"}) # tuples of hashable items are fineIf you define __eq__ on a class, Python sets __hash__ to None, which makes instances unhashable. You must define both together so they agree:
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))
seen = {Point(1, 2)}
print(Point(1, 2) in seen)The hash uses exactly the fields that equality uses. If __hash__ used a field that __eq__ ignores, two equal points could get different hashes and break rule 1.
Common errors
- Hashing with a function that is not deterministic. If the hash depends on memory address, time, or random state that differs between calls, the same key maps to a different bucket on the next lookup. Python's
hash()for strings is randomized per process, so it is safe inside one running program but wrong for anything you save to disk or share between processes. Use a stable hash for those cases. - Mutating a key after insertion. The entry stays in its old bucket and lookups with the new value miss it. Use immutable keys.
- Equality and hash disagreeing. Defining
__eq__over some fields and__hash__over others causes lookups to fail intermittently, and only for some inputs. - Using
%on a hash with a poor low bits pattern. The modulo uses the low-order part of the hash. A hash whose low bits are predictable, such as one that always returns even numbers, leaves half the buckets empty when the bucket count is even. The next chapters return to this. - Never resizing. With a fixed bucket count, the load factor keeps rising as you add entries, and chains get longer. Real tables grow, usually doubling the bucket count when the load factor passes a threshold, and then reinsert every entry. Reinsertion is needed because the index depends on
len(buckets).
What to take forward
A hash table trades a search for a computation: hash the key, reduce it to an index, and check a short bucket. The hash function carries the performance. It must be deterministic, consistent with equality, and evenly distributed, and it should be cheap. The next chapters make each of those requirements precise and show how they fail.
Exercise
A table has 16 buckets and holds 64 entries, and its hash function spreads keys evenly. Roughly how many entries does a typical bucket hold, and what happens to that number and to lookup cost if the hash function instead sends every key to bucket 0?
Show answer
The load factor is 64 / 16 = 4, so a typical bucket holds about 4 entries and a lookup compares about 4 keys on average, which is constant with respect to table growth. If every key goes to bucket 0, that bucket holds all 64 entries and the other 15 are empty, so each lookup scans up to 64 entries. Lookup cost becomes O(n) instead of O(1).
Exercise
You write a class with __eq__ that compares name and age, and a __hash__ that returns hash(name). Is the table correct? What would break if __hash__ returned hash((name, age, id(self))) instead?
Show answer
The first version is correct. Equal objects have equal names, so they have equal hashes, which satisfies the rule that equal keys have equal hashes. Objects that differ only in age share a hash, which is a harmless collision resolved by ==. The second version breaks the rule, because two equal objects have different id(self) values and so almost always different hashes. They land in different buckets, and a lookup with an equal but separate object fails to find the stored one.