4/40
Part 1 of 7 · Sets and seen-setsLearn and do

Collisions stay rare because the table is never more than two thirds full

Now add 26 to the table of 8 buckets. 26 % 8 is 2, and 42 is already in bucket 2. Two keys that want the same bucket are a collision. The table has to put 26 in another bucket, by a fixed rule, and find it there later.

What matters for now is how often it happens. CPython keeps at most two thirds of the buckets full, and grows the table when it gets there. So most lookups land on the right key on the first try.

That gives two numbers for every operation:

  • The average case is the cost when the hash spreads the keys evenly over the buckets, which ordinary keys do. A lookup, an insert and a delete each cost O(1).
  • The worst case is when the keys pile into the same buckets. The Python docs say that when every key hashes to the same value, each of those O(1) operations takes O(n) time instead. A class whose __hash__ returns the same number for every object does exactly that.

The free buckets cost memory. A set's own table for a million integers is about 4 times a list's:

sys.getsizeof, one million integers, the container alone
list(...)
8.0 MB
set(...)
33.6 MB
dict.fromkeys(...)
41.9 MB

The dict is about 5 times. That's before the integers themselves, which all three share.

Building costs time too. set(ids) took 11.8 ms for a million integers, about three full list scans.

So a set pays off when you look up many times. If you check one value once, scan the list.

Each bucket has to be its own list. [[] for _ in range(n)] makes n separate empty lists: it's a list comprehension, an expression followed by a for that says how many times to build it. [[]] * n looks the same but repeats one list n times, so appending to any bucket appends to all of them.

In the editor, write bucket_table(keys, n): n empty buckets, with every key appended to bucket hash(key) % n. Then write collisions(table): how many keys landed in a bucket that already held a key.