Sub topic 7
Inside a hash table: buckets and indexing
This chapter assumes you know basic Python, how list indexing works, and the idea of O(1) time. It shows how a hash table turns a key into a position in an array, so lookups don't have to scan every item.
The core idea
A hash table is an array of slots called buckets. To store or find a key, the table computes a number from the key and uses it to pick one bucket. It then looks only in that bucket.
The hash function from the previous chapter produces a large integer. That integer is usually far bigger than the array, so the table shrinks it to a valid index. The usual way is the remainder operator:
index = hash(key) % number_of_bucketsWith 8 buckets, every key maps to an index from 0 to 7.
Because the previous line would be incorrect inside the required format, here is the diagram as specified:
Why indexing is fast
Reading buckets[5] takes the same time whether the array holds 10 buckets or 10 million. The table does a fixed amount of work to compute the index, then jumps straight to it. It never scans the whole collection. That jump is where the average O(1) cost comes from.
A minimal implementation
The class below stores each bucket as a list of (key, value) pairs. Equality is checked only inside the chosen bucket.
class ChainedMap:
def __init__(self, bucket_count=8):
self._buckets = [[] for _ in range(bucket_count)]
self._size = 0
def _bucket(self, key):
return self._buckets[hash(key) % len(self._buckets)]
def put(self, key, value):
bucket = self._bucket(key)
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self._size += 1
def get(self, key, default=None):
for k, v in self._bucket(key):
if k == key:
return v
return default
m = ChainedMap()
m.put("a", 1)
m.put("b", 2)
m.put("a", 3)
print(m.get("a"), m.get("b"), m.get("z")) # 3 2 NoneFollow m.put("a", 3):
_buckethashes"a"and reduces it to a bucket index.putscans that one bucket for a key equal to"a".- It finds the earlier pair and replaces the value. Nothing is appended, so
_sizestays the same.
get("z") hashes to some bucket, finds no equal key there, and returns the default.
Two comparisons, two jobs
Lookup uses the hash and equality for different purposes. The hash only chooses the bucket. Equality (==) decides whether a stored key is the one you want. Two different keys can land in the same bucket, so the hash alone cannot confirm a match.
Summary of the lookup steps
| Step | Work done | Cost |
|---|---|---|
| Hash the key | Compute an integer | Depends on key size |
| Reduce to an index | Remainder by bucket count | Constant |
| Jump to the bucket | Array access | Constant |
| Compare keys | Check equality in that bucket | Depends on bucket length |
The last step is the only one that grows when the table is crowded, which is why bucket length matters.
Exercise
A table has 8 buckets and a key whose hash is 21. Which bucket index is used? Why must the table still compare keys after reaching that bucket?
Show answer
The index is 21 % 8 = 5. Different keys can share a bucket, so the table must check equality against each stored key there to find the exact match.