Sub topic 3
Hash functions: turning keys into integers
This chapter assumes you can read short Python programs, know what the modulo operator does, and understand introductory Big-O notation. It covers how a hash function behaves and why the usual designs look the way they do. It does not cover how the integer becomes a bucket position, or what happens when two keys land in the same place. The next two chapters cover those.
What a hash function does
A hash table needs an integer from each key, because only an integer can pick a position in an array. A hash function is a function that maps a key of any type, such as a string, a tuple, or a number, to a fixed-size integer. That integer is the key's hash value, or hash code.
The function must be cheap to compute. If hashing a key cost as much as scanning a list of all stored keys, the table would gain nothing.
The properties a good hash function needs
| Property | Meaning | What breaks without it |
|---|---|---|
| Deterministic | The same key always gives the same hash during one run. | Lookups miss entries that are present. |
| Consistent with equality | If `a == b`, then `hash(a) == hash(b)`. | Equal keys land in different places, so lookups fail. |
| Uniform | Hash values spread evenly over the output range. | Many keys share positions and operations slow down. |
| Fast | Cost is proportional to the key's size, with a small constant. | The hash cost swamps the benefit of the table. |
| Sensitive to input | Similar keys get very different hashes. | Patterned data, such as sequential IDs, clusters. |
The first two are correctness rules. The last three are quality goals. A function that returns 0 for every key is a valid hash function. The table would still return correct answers, but every key would compete for one position, and lookups would degrade to a linear scan.
Note that the rule goes one way. Equal keys must have equal hashes. Unequal keys may share a hash, and some always will. The chapter on collisions explains why.
A first example: a polynomial string hash
Here is the function from the spine, which combines the characters of a string one by one and then reduces the result to a table size:
def string_hash(s, size):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) % size
return h
print(string_hash("apple", 8))
print(string_hash("apple", 8) == string_hash("apple", 8))This prints 2 and then True. The second line shows determinism. The loop does the real work, in two steps.
ord(ch)turns each character into its integer code point.h * 31 + ...multiplies the running value before adding the next character, so the result depends on character order as well as content.
The % size at the end of each step reduces the value to a table size. That reduction is the next chapter's subject, so here it only keeps the numbers small.
Because of the multiplication, this is called a polynomial hash. For the string c0 c1 c2, the value is c0*31^2 + c1*31 + c2. The multiplier 31 is a small odd prime. It has a long history in Java's String.hashCode, and it makes the multiplication cheap on older hardware. Many other multipliers work.
Why order must matter
The simplest hash for a string sums the character codes. It is fast and deterministic, and it is poor. Compare it with the polynomial version:
def sum_hash(s):
return sum(ord(c) for c in s)
def poly_hash(s):
h = 0
for ch in s:
h = (h * 31 + ord(ch)) & 0xFFFFFFFF # keep 32 bits
return h
print(sum_hash("ab"), sum_hash("ba"))
print(poly_hash("ab"), poly_hash("ba"))
print(poly_hash("Aa"), poly_hash("BB"))The output is:
195 195
3105 3135
2112 2112The sum hash cannot tell any anagram from another, so "listen" and "silent" always share a hash. The polynomial hash separates "ab" and "ba". It still collides on "Aa" and "BB", because 65·31 + 97 and 66·31 + 66 are both 2112. No simple function removes every collision. The aim is to make collisions look random, not to prevent them.
The & 0xFFFFFFFF in poly_hash keeps only the lowest 32 bits. Python integers have unlimited size, so without this mask a long string would produce an enormous integer. Languages with fixed-width integers get this truncation for free, by overflow. Fixed output width is part of the definition of a hash function.
Spreading changes: the avalanche idea
A strong hash function has the avalanche property. Changing one input bit should flip about half of the output bits, unpredictably. The polynomial hash above does not have it. Strings that differ only in the last character have hashes that differ by a small amount, so nearby inputs give nearby outputs.
That weakness matters when the output is later reduced modulo a table size. Patterned keys, such as "item1", "item2", "item3", then fill adjacent positions in an orderly way. This can be fine or harmful depending on the table size. Production hash functions add a mixing step, usually a few multiplications, XORs, and bit shifts, to destroy this regularity. Examples are MurmurHash, xxHash, and SipHash. You do not need to memorize their internals. You need to know why they exist: they make similar inputs produce unrelated outputs.
How Python computes hashes
Python exposes the built-in hash(), and its dict and set use it. Some facts you can check yourself:
print(hash(42)) # an int hashes to itself (for small values)
print(hash(1) == hash(1.0) == hash(True))
print(hash((1, 2)) == hash((1, 2)))
print(hash(-1)) # -2 in CPythonThe output is:
42
True
True
-2Several behaviors here are worth understanding.
- Equal values across types share a hash.
1 == 1.0 == Truein Python, so the equality rule forces their hashes to match. This is why{1: "a"}[1.0]works. hash(-1)is-2. CPython uses-1internally as an error signal from the C function, so it remaps that one value. User code should not depend on exact hash values.- Strings are salted. Run
python -c "print(hash('apple'))"twice and you will usually get two different numbers. Each process picks a random secret seed for string hashing. The hash is still deterministic within one run, which is all the table needs, but the value must never be stored in a file or sent to another machine. The environment variablePYTHONHASHSEED=0fixes the seed, which is useful for reproducible tests. The reason for salting appears in the chapter on hash flooding.
Custom classes get an identity-based hash by default. If you define __eq__ on a class, Python sets __hash__ to None, which makes instances unhashable. You must then define __hash__ yourself to match. The chapter on key requirements covers that rule.
Common mistakes
- Hashing mutable state. If a key's hash depends on a field that later changes, the stored entry sits at the old position and cannot be found again.
- Mixing equality and hashing. Writing
__eq__that ignores a field while__hash__includes it breaks the consistency rule. - Persisting hash values. Python's string hashes change between runs. A file that stores
hash(name)as an ID will not match the next time the program runs. Use a stable digest, such as one fromhashlib, for that purpose. - Confusing table hashes with cryptographic hashes. SHA-256 resists deliberate collision-finding but is much slower than table hashes. Table hashes need speed and good spread, not resistance to every attack. Using a fast table hash for passwords or integrity checks is a security error.
- Assuming the output is the index. The hash value is usually far larger than the array. A separate step maps it into a valid position.
Summary of the model
A hash function turns a key into a fixed-size integer. It must give the same value for equal keys, and it should spread different keys evenly. The polynomial form shows the basic structure: read the contents in order, combine each element with a multiplication and an addition, and keep a fixed width. Real libraries add stronger mixing and, for strings, a random seed.
Exercise
A programmer defines a hash for 2D points as x + y, then stores points (1, 4), (2, 3), (3, 2), and (4, 1) in a table. Which hash properties does this function satisfy, which does it fail, and what would you change?
Show answer
It is deterministic and consistent with equality, because equal points have equal coordinates and so equal sums. It is fast. It fails uniformity and input sensitivity. All four points sum to 5, so they share one hash value and will compete for the same position, and every point on the same anti-diagonal does the same. The fix is to combine the coordinates in an order-sensitive way, for example hash((x, y)) or x * 31 + y masked to a fixed width, so that (1, 4) and (4, 1) differ.
Exercise
Why does {1: "a"}[True] return "a" in Python, and what does this tell you about the relationship between equality and hashing?
Show answer
True == 1, so Python requires hash(True) == hash(1). Both give 1. The lookup finds the same position and then confirms the keys are equal. The example shows that the hash rule follows equality. Whenever two values compare equal, they must hash equal, even if their types differ.