Skip to content

What a Python list is in memory

Working knowledgeUnder the hood

Indexing a Python list is instant, append is almost always cheap, and yet insert(0, x) and x in lst crawl on big lists. All three follow from one layout: a row of pointers with spare room at the end.

01 The puzzle

Python lists hold anything: ints, strings, other lists, all mixed. They also grow without you ever saying how big they will be. A C array can do neither. So what is the object behind []?

Everything below is about CPython, the interpreter you get from python.org, on a 64-bit machine. Other interpreters such as PyPy store lists differently.

02 A row of pointers, not values

A list does not store your values. It stores pointers to them, 8 bytes each, in one contiguous block called ob_item. Each value is a separate object somewhere else on the heap, with its own type and reference count.

lst = [7, 'hi', 7]
lst · pointer slots
→ #A0
→ #B1
→ #A2
objects on the heap
#A→int 7 · 28 bytesused twice#B→str 'hi'
  • the same object

Both 7 slots hold the same address. CPython caches the small ints from -5 to 256, so every 7 in the program is one object.

That is why a list can mix types: every slot is the same size, whatever it points to. It is also why lst[i] is fast. The address of slot i is the start of the block plus 8 × i, one sum and one read, however long the list is.

Next to the pointer block, the list header keeps two counts: ob_size is the length you see with len(), and allocated is how many slots the block really has. The gap between them is spare room.

03 What append really does

Watch the two counts while you append eight ints to an empty list. Most appends just fill a spare slot. Only when the block is full does CPython ask for a bigger one.

Eight appends to an empty list
Step 1 of 9
allocated 0Resizes 0
ob_item · the pointer slots
—0
—1
—2
—3
—4
—5
—6
—7
int objects the slots point to
Empty
  • just stored
  • in use
  • copied on resize
  • spare slot
  • not allocated

lst = [] makes the list header only. ob_item is NULL and allocated is 0: there is no slot array yet.

0 len

04 Over-allocate, so append stays cheap

When it must resize, CPython (3.9 and later) asks for about an eighth more than the new length, plus a little, rounded down to a multiple of 4: roughly n + n // 8 + 6. Starting from empty, allocated goes 4, 8, 16, 24, 32, 40, 52, 64 and so on. Older versions used a slightly different formula, so the exact steps vary, but the idea is the same.

Grow by exactly oneCopy on every appendAppend number n copies n − 1 pointers, so n appends copy about n²/2 in total.
Grow by a fractionCopy now and thenEach resize buys room in proportion to the size, so the copying averages out to a constant per append: amortised O(1).

The price is memory. Right after a resize, up to about an eighth of the slots sit unused. For a list you build once and keep, that is a small cost for never having to say the size up front.

05 Watch the resizes yourself

sys.getsizeof reports the list header plus its pointer block. It does not count the objects the pointers lead to. Print it whenever it changes:

grow.py
import sys
lst = []
last = sys.getsizeof(lst)
print(f"len 0: {last} bytes")
for i in range(40):
lst.append(i)
size = sys.getsizeof(lst)
if size != last:
print(f"len {len(lst):2}: {size} bytes")
last = size
Text
len 0: 56 bytes
len 1: 88 bytes
len 5: 120 bytes
len 9: 184 bytes
len 17: 248 bytes
len 25: 312 bytes
len 33: 376 bytes

The empty list is a 56-byte header. Each jump is 8 bytes per new slot: 4 slots at length 1, then 8, 16, 24, 32, 40. Your numbers may differ slightly on another CPython version, but the pattern of rare, growing jumps is the same.

06 What each operation costs

List operations in CPython, for a list of length n
OperationCostWhy
lst[i]O(1)One address sum, one read
len(lst)O(1)Reads the stored length
lst.append(x)O(1) amortisedUsually one write into a spare slot
lst.pop()O(1)Takes the last pointer; nothing shifts
lst.insert(0, x)O(n)Shifts every pointer one slot right
lst.pop(0)O(n)Shifts every pointer one slot left
x in lstO(n)Compares x with each element in turn

07 When the layout bites

[[]] * 3 does not make three lists. It makes one list and three pointers to it, so appending to grid[0] shows up in every row. Build rows with [[] for _ in range(3)].

grid = [[0] * 3] * 3Repeating a list repeats the pointerThe outer * 3 copies the pointer to one inner list. Change grid[0][0] and all three rows change.
while q: q.pop(0)Using a list as a queueEach pop(0) shifts every remaining pointer. Use collections.deque, which removes from either end in O(1).
if x in seen_list:Membership tests in a loopA list has no index of its values, so in checks them one by one. Inside a loop that is O(n²). A set hashes the value and finds it in O(1) on average.
[0.5] * 1_000_000Big lists of numbersEach float is its own 24-byte object plus an 8-byte pointer. Here they all share one object, but a million different floats cost about 32 MB. array.array("d") or NumPy stores the raw 8-byte values instead.
sys.getsizeof(lst)Measuring only the shellIt counts the header and the pointer block, never the objects. Lists of large strings look tiny.

08 Check yourself

Question

A list has len 5 and allocated 8. What does lst.append(x) do?

Question

After grid = [[0] * 3] * 3 and grid[0][0] = 1, what is grid?

Question

Why is lst[500_000] fast while 500_000 in lst is slow?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?