Log inStart free
LESSON 1.02 · 6 STAGES · 4 CONTROLS · 3 CHECKS

Python containers under the hood

Watch a list grow, a tuple rebuild, and a dict find keys by hash.


EXPLAINER · 1.02 · CONTAINER BAY
01
Stage 1 of 6 · Array of slots
A list is a dynamic array. Its block has 4 slots, and 1 slot is spare.
Explain it simply

Python keeps a list as one row of slots in memory. Each slot holds a pointer to an item. The row has a spare slot at the end, so the next item has room. Because the slots sit side by side, Python finds slot 2 at once.

The list holds 3 items in a block of 4 slots at address 4800.

item, key, hashslot, block, size, maskcopy, collision, freednew item, chosen slot
Toy: 6 to 24 items · 6 int or word keys (hash seed 0) · CPython 3.12, 64-bit sizes · addresses are stand-ins
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
list.append
A list with spare slots, or a tuple.
12
How many items the loop adds.
dict
A dict with values, or a set of keys.
numbers
Small ints, or words hashed with seed 0.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
addr(i)=start+8 i\mathrm{addr}(\sy{i}{data}{i}) = \sy{start}{param}{\mathrm{start}} + 8\,\sy{i}{data}{i}
addr(2)=4800+8⋅2=4816\mathrm{addr}(2) = 4800 + 8 \cdot 2 = 4816

Each slot sits 8 bytes after the slot before it.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import sys

a = []
size = sys.getsizeof(a)
for i in range(12):
    a.append(i)
    if sys.getsizeof(a) != size:  # the list got a bigger block
        size = sys.getsizeof(a)
        print(len(a), size)    # 1 88 | 5 120 | 9 184

print(hash(7))                 # 7  (a small int is its own hash)
d = {}
for k in [1, 4, 7, 9, 12, 2]:
    print(k, hash(k) & 7)      # first slot to try: 1→1 4→4 7→7 9→1 12→4 2→2
    d[k] = 'abcdef'[len(d)]
print(list(d))                 # [1, 4, 7, 9, 12, 2]  (insertion order)

Save it as demo.py and run PYTHONHASHSEED=0 python3 demo.py with 64-bit CPython 3.12. The fixed seed keeps word hashes the same on every run; other versions can print other sizes.

Common mix-ups

MYTHlist.append copies the whole list every time.

FIXA list keeps spare slots. Most appends write one slot. Only a full list gets a bigger block and copies.

MYTHA dict lookup checks every key until it finds a match.

FIXThe hash picks one slot. A lookup reads that slot, and reads more slots only after a collision.

Predict, then reveal
0 / 3 REVEALED
Q01When a 6th item is added to a tuple, how many old pointers does it copy?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02With 24 appends to a list, is the cost per append near 2 or near 12?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03As keys are added, which hash table grows first: the dict or the set?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. A list keeps spare slots, so an append costs about 2 writes on average.
  2. A tuple cannot grow: every addition copies the whole tuple.
  3. A dict or a set finds a key by its hash, not by a search.