The hash picks a bucket, so a lookup is O(1) on average
How can a set skip the scan? Before it stores a key, it turns the key into a number, and the number says where the key goes.
keys = [12, 33, 7, 42]print([hash(k) for k in keys])print([hash(k) % 8 for k in keys])
Predict
For a small int, hash(k) is k. A table of 8 buckets files a key under hash(k) % 8. Which bucket does 42 go in?
Pick one to see what it prints.
Each key goes to the bucket its hash names:
The table, 8 buckets
buckets
012345673342127
12 goes to bucket 4, 33 to 1, 7 to 7 and 42 to 2.
Three words you'll use for the rest of the lesson:
A key is the value you look things up by: an element of a set, or the left side of a dict entry.
hash(key) turns the key into an integer, its hash. The same key always gives the same hash within one run of Python.
The table behind a set or a dict has a fixed number of slots, called buckets. The hash picks the bucket. With 8 buckets, Python uses the hash's last three bits. For these small integers that's the same as hash % 8.
Pick an answer above to see the rest
Predict
To check whether 33 is in the table, how many of the other keys does the lookup compare it with?
To check whether 33 is in the table, Python works out bucket 1 and looks there. It never touches 12, 7 or 42. That's the whole trick.