Python containers under the hood
Watch a list grow, a tuple rebuild, and a dict find keys by hash.
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.
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.
Takeaways
- A list keeps spare slots, so an append costs about 2 writes on average.
- A tuple cannot grow: every addition copies the whole tuple.
- A dict or a set finds a key by its hash, not by a search.