Containers

A list in Python is an array of pointers, not an array of values. From that one sentence you can derive the growth law, a thousandfold difference between append and insert(0), and why a million numbers weigh thirty-six megabytes instead of eight.

L1 · 8 minL2 · 12 min📱 phoneverified · CPython 3.11, linux x86-64

1Predict

Snippet A
import sys
l = []
for i in range(10):
    print(len(l), sys.getsizeof(l))
    l.append(i)
len:   0   1   2   3   4   5   6   7   8   9
bytes: 56  88  88  88  88 120 120 120 120 184
The size grows in jumps, and the jumps are uneven.
Snippet B
import timeit
print(timeit.timeit("l.append(1)", "l=[]", number=100_000))
print(timeit.timeit("l.insert(0,1)", "l=[]", number=100_000))
0.0013
1.5814
The very same insertion of one element. A difference of twelve hundred times.
Snippet C
import sys
print(sys.getsizeof((1, 2, 3)))
print(sys.getsizeof([1, 2, 3]))
64
88
The same contents, a difference of twenty-four bytes.
Snippet D
big  = list(range(200_000))
bigs = set(big)
# how long will 200 checks of "is the last element inside?" take
in a list   0.204 s
in a set    0.000012 s
Seventeen thousand times. The operator is one and the same — in.

2Mechanism

From lesson 01: a name is a reference to an object. A container is an object that holds the same kind of references. Everything below follows from that.

A list is a contiguous array of pointers plus two numbers: how many slots are in use and how much room is allocated. The objects themselves lie anywhere on the heap; the list knows only their addresses.

The array is allocated with spare room. Otherwise every append would require a reallocation and a copy.

Consequence 1 · the growth law and amortized cost

When the slots in use become as many as the slots allocated, the list asks for a new block by the formula new = size + size/8 + constant — roughly ×1.125, not ×2 as in std::vector.

Snippet A shows this directly: 56 bytes for an empty list (just the header), 88 after the first append — room for four pointers was allocated — then a jump at the fifth element, then at the ninth. The jumps become rarer but bigger.

Hence the amortized O(1) of append: reallocation happens rarely, and the cost of copying is spread out. And hence the choice of the 1.125 factor as a trade: less memory wasted, more frequent copying. C++ chose a different point on the same trade-off.

Consequence 2 · inserting at the front shifts everything

The array is contiguous, so inserting an element at the front means shifting every existing pointer one position to the right. For a list of N elements that is N operations; for a loop of N insertions, N².

Snippet B: 0.0013 seconds versus 1.58. The difference is not a “slow method” but the fact that append writes into the free tail while insert(0, …) moves the whole array. The same logic applies to pop(0) and del l[0].

If you need both ends, there is collections.deque: a doubly linked list of blocks in which adding and removing at either end costs O(1). At the price of indexed access into the middle becoming O(n).

Consequence 3 · a tuple is cheaper because it does not grow

Snippet C. A tuple is immutable, so it does not need the “how much is allocated” field — the size is known forever, and the pointers live right in the body of the object rather than in a separate block. One allocation instead of two, 24 bytes less.

Immutability gives a second thing as well: a tuple can be a dictionary key and a list cannot. And a third, less well known: CPython keeps free lists of small tuples and reuses them, because tuples are created and die en masse — on every unpacking, on every return of several values.

Consequence 4 · in on a list is a scan

A list knows nothing about its elements except their addresses. So the check “is x in here” can only be a linear scan comparing each element. There is no search structure in a list and there cannot be one.

A set and a dictionary are built differently: they compute a hash and go straight to the right bucket. Hence snippet D and a difference of seventeen thousand times. There is one in operator, but the mechanisms behind it are fundamentally different — and choosing the data structure here is not a micro-optimization but a choice of complexity class.

How a set works inside is in lesson 05. Here the conclusion is enough: if a collection is searched, it should not be a list.

Consequence 5 · the memory of a list of objects is two sums, not one

Since a list stores pointers, its own size is 8 bytes per element. But the objects themselves live separately, and they have to be counted too. From lesson 02 we know an integer weighs 28 bytes:

a million integersmemory
the array of pointers in the list8 MB
a million int objects28 MB
total~36 MB
numpy.arange with int648 MB
the same with int324 MB

That is all of numpy in one line: it does not speed the model up, it takes homogeneous data out of it. No objects, no pointers — one contiguous buffer that compiled code works on. The ninefold difference in memory and the orders of magnitude in speed come from here, not from “C is faster”.

Meanwhile sys.getsizeof lies honestly: it shows only the list itself, without its contents. For the full picture you need a traversal or tracemalloc.

3Limits of the model

Where this stops holding

Shrinking exists, but not always. A list does reduce its allocated block — but only when the slots in use fall below half of those allocated, and not down to the actual size but by the same formula, with spare room. Removing one element out of a thousand returns nothing; removing nine hundred returns almost everything. This is worth checking on your own version with a measurement rather than by trusting the text 🔧.

A slice copies. l[:] and l[10:20] create a new list with new pointers — and from lesson 01 we know the copy is shallow. A list has no copy-free view of its data; memoryview and numpy do, but only for buffers, not for objects.

The growth numbers are an implementation detail 🔧. The formula has changed and may change again; only the amortized complexity of the operations written in the documentation is guaranteed, not the specific size of the allocated block.

4Root

The same root R1: a value is an object, a container stores references. Python had no alternative — since elements can be anything and of any size, storing them by value in a contiguous array is physically impossible.

Hence an honest statement of the trade-off. A Python list is a universal structure: heterogeneous, growing, accepting any objects. Universality is paid for with an indirection on every access and with separate memory. The specialized structures in the standard library — array.array for homogeneous numbers, bytes and bytearray for bytes, deque for queues — exist precisely as targeted opt-outs from that universality where it is not needed.

5Analogy

A list of objects versus a numpy array is exactly the same fork as a sparse representation versus a dense one. A list stores addresses and lets the elements be anything and lie anywhere; a dense array fixes the type and the layout and gets sequential access and cache-friendly work in return.

And the consequence carries over: just as element access in sparse matrices is more expensive than in dense ones, traversing a list of objects is more expensive than traversing a buffer, even when the operation is the same. The reason is identical — a pointer that has to be followed.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

Why does a list store pointers and not the values themselves — could it not have been otherwise?

It could not, as long as a list has to accept anything. An array of values requires all elements to be the same size; a Python list has to store a number, a string and a function side by side.

This is a direct consequence of R1. Since a value is an object on the heap, the only thing that fits into a fixed-size cell is an address. All the behaviour follows: traversing a list is jumping around the heap rather than reading sequentially, which is why the CPU cache works poorly and a million numbers cost 36 MB instead of 8.

Otherwise is possible, and the standard library has it:

import array, sys
a = array.array("q", range(1_000_000))     # signed 8-byte
print(sys.getsizeof(a) / 1e6, "MB")        # → about 8
print(sys.getsizeof(list(range(1_000_000))) / 1e6, "MB")  # → about 8 plus the objects themselves

array stores values, not references — and pays for it by having the type fixed at creation. numpy does the same, adding dimensions and vector operations. The choice is not between “right” and “wrong” but between homogeneity and universality, and Python made universality the default.

Why is list.pop(0) slow while deque.popleft() is not?

Because they are different data structures, not different implementations of one.

A list is a contiguous array of pointers. Removing from the front has to shift all the remaining elements one position to the left: N operations of memmove. A deque is a doubly linked list of blocks of 64 pointers, and removing from either end is a shift of an index within a block.

import timeit
print(timeit.timeit("while l: l.pop(0)", "l=list(range(100_000))", number=1))
print(timeit.timeit("while d: d.popleft()",
                    "import collections; d=collections.deque(range(100_000))", number=1))
# → 0.738
# → 0.0035        213 times

213 times on a hundred thousand elements, and the gap grows linearly with length — it is the difference between O(n) and O(1) per operation, that is, between O(n²) and O(n) for the loop.

The price of deque: indexed access into the middle is O(n), because you have to walk the blocks. The rule of choice is simple: if you access by index, a list; if you add and remove at the ends, a deque. A queue, a buffer of the last N events, a breadth-first traversal — all of these are a deque.

A tuple is faster than a list — is that worth economizing on?

On creation — yes, noticeably. On traversal — not at all. And knowing exactly where the difference is beats a general “tuples are faster”.

import timeit
print(timeit.timeit("(1,2,3,4,5)", number=3_000_000))
print(timeit.timeit("[1,2,3,4,5]", number=3_000_000))
# → 0.022
# → 0.131        5.9 times

s = "t=tuple(range(1000)); l=list(range(1000))"
print(timeit.timeit("sum(t)", s, number=20_000))
print(timeit.timeit("sum(l)", s, number=20_000))
# → 0.127
# → 0.135        no difference

Where the sixfold difference on creation comes from. Not from “a tuple is lighter”: a tuple of literals is folded whole into a constant by the compiler (lesson 22, phase 5), and creating it is just loading a ready-made object. A list cannot be a constant; it is assembled by instructions on every pass.

Hence the right conclusion: the gain is not in the type but in the fact that something immutable can be computed in advance. A tuple of computed values is assembled almost the same way as a list.

Choose between them by meaning — “a fixed record of heterogeneous fields” versus “a homogeneous sequence of variable length” — and from that choice follow hashability, 64 bytes versus 88, and the ability to become a dictionary key.

Where does the list growth law come from, and why not doubling?

Because doubling is a poor trade on small lists, and they are the overwhelming majority.

CPython grows the buffer by about 12.5% beyond what is needed, with rounding and with special rules for the first few elements. The sequence is directly visible:

import sys
l = []
prev = -1
for i in range(70):
    if sys.getsizeof(l) != prev:
        prev = sys.getsizeof(l)
        print(len(l), prev)
    l.append(i)

Why not 2×. Doubling gives on average 50% of wasted memory; at 12.5% the amortized complexity of append stays O(1) while the waste is four times smaller. For a language where a program has tens of thousands of lists and almost all of them are short, that is the better deal.

And the reverse operation exists, contrary to the common “a list never shrinks”:

l = list(range(1000))
print(sys.getsizeof(l))       # → 8056
del l[100:]
print(sys.getsizeof(l))       # → 984    the buffer shrank

The specific numbers are 🔧 through and through: the formula has changed and may change. Only the amortized complexity written in the documentation is guaranteed. A test that compares a list's getsizeof with a constant will break on the next release.

Bottom line. A list is a contiguous array of pointers with spare room, growing by about one eighth when it fills up: hence the amortized O(1) of append and the linear cost of insert(0), which gives a difference of twelve hundred times in the measurement. A tuple is 24 bytes cheaper because it is immutable and needs no spare-room field. An in check on a list is a scan, because a list knows nothing about its elements except their addresses; the same operation on a set is four orders of magnitude faster, and that is a choice of complexity class, not a micro-optimization. And the memory of a list of objects is made up of two sums — the pointers and the objects themselves — which is why a million integers take thirty-six megabytes instead of eight. That arithmetic is exactly what makes numpy not an accelerator but a way out of the object model.
From here on — optional
counterfactualC++, Java, Go — values in place versus pointersArrayList<Integer> suffers from the same thing; vector<int> and Go slices do not
Counterfactual · the same questions elsewhere

C++ std::vector<int> stores values directly: a million numbers is eight megabytes in one piece, and a traversal stays within the CPU cache. The price is that a vector is homogeneous in type, and that is known at compile time.

Java's ArrayList<Integer> suffers from the same thing as Python: it is an array of references to wrapper objects, with the same doubled memory and the same indirection. That is exactly why Java keeps numbers in int[] rather than in an ArrayList — the very “two sets of rules” discussed in lesson 02.

Go stores values in a slice directly, but len and cap are exposed and visible to the programmer: growth is managed by hand through make with spare capacity. Python hides the same thing inside and decides for you.

🐛 154×Deduplication through “not in list”A check against a list inside a loop is a loop within a loop: 0.058 s versus 0.0004 s
🐛 The bug that passes review

Order-preserving deduplication. Reads perfectly, runs quadratically.

result = []
for item in items:
    if item not in result:      # ← right here
        result.append(item)

The code is obvious and correct: walk the elements, add the ones that are not there yet. The reviewer sees a clear intent and approves. But item not in result is a scan of the whole accumulated list on every iteration — consequence 4 inside a loop: N² complexity.

9000 elements, three runstime
check against a list0.058 s
check against a set0.0004 s

A hundred and fifty times, and that is on ten thousand elements. On a hundred thousand the difference will be a hundred times greater than this. The treachery is that on test data of fifty records the code runs instantly, and the problem appears only at real volume — that is, after release.

seen = set()
result = []
for item in items:
    if item not in seen:
        seen.add(item)
        result.append(item)

A rule derived from the mechanism, not from experience: if there is an in on a list inside a loop, it is a loop within a loop. Search in a set or a dictionary and keep the list for order. The same mistake in another guise is list.remove and del l[0] in a loop: both operations are linear.

⚡ 9×Homogeneous numbers outside the object model36 MB in a list versus 8 MB in array and 4 MB in numpy int32
⚡ A ninefold memory saving on homogeneous data

A million numbers in a list versus a million numbers in a buffer. The difference is not in the speed of the language.

a million integersmemory
list(range(...))~36 MB
array("q", ...) from the standard library8 MB
numpy.arange(..., dtype=int32)4 MB

Thirty-six megabytes are made up of eight for the array of pointers and twenty-eight for the objects themselves — straight from consequence 5. Both alternatives remove both: the numbers are stored by value, with no headers and no pointers.

What to choose. If you only need compactness and the standard library, array.array: it is everywhere and needs no dependencies. If you also need vector operations, numpy. If the data is heterogeneous or the objects are complex, stay with a list, because the alternatives do not apply to them.

Where this really decides things. Not where there are a thousand numbers — there the difference is unnoticeable. But where a collection lives in a service's memory permanently: a table of coordinates, a metrics buffer, an index of identifiers. Thirty-six megabytes per worker versus four, with twenty workers, is already the difference between “fits” and “does not fit”.

💻 terminalCheck it in the REPLFour snippets plus shrinking, list multiplication and the honesty of getsizeof

Check it yourself

Run the four snippets and check them against your prediction. Then:

l = list(range(1000))
sys.getsizeof(l)
del l[100:]
sys.getsizeof(l)
# Did the memory come back? And if you re-create the list?

a = [1, 2, 3]
b = a * 3
sys.getsizeof(b)
# How many times bigger, and why not exactly three?

import array
arr = array.array("q", range(1_000_000))
sys.getsizeof(arr), sys.getsizeof(list(range(1_000_000)))
# Why is getsizeof honest for array but not for a list?

# Without code: why can a tuple be a dictionary key,
# while a tuple with a list inside cannot?

The third question is the most important one: it is about getsizeof measuring an object, not the graph reachable from it, and that is a trap in any memory measurement.

sourceheapq and dequeA heap on a list works only because a list is an array

Where it lives in real code

Lib/heapq.py is a hundred and fifty lines of pure Python in which an ordinary list is used as a binary heap. The indices of the children are computed by arithmetic: element i has children 2i+1 and 2i+2.

Notice why this works: indexed access to a list is constant-time because it is an array. On a linked list the same heap would be pointless. The whole data structure exists thanks to the property from consequence 1, and it is a good example of how memory layout determines which algorithms are possible at all.

The second place is Lib/collections/__init__.py. Look at what deque was introduced for, and at how its documentation says outright: O(1) at both ends versus O(n) for a list. The standard library does not hide the trade-off here — it names it.

L2The layout of a list and the price of indirectionThe full table of growth jumps and the price of indirection during traversal

From L1 you know that a list is an array of pointers with spare room. Here: the exact structure, and what an extra hop through an address costs.

A list object consists of a variable-length header (24 bytes: reference count, type, length), a pointer to the array of elements, and the allocated field. In total 56 bytes for an empty list. The array of pointers itself is allocated separately — a second allocation, which also explains why getsizeof of an empty list is not zero, and why the size after the first append jumps by 32 bytes at once: room for four pointers was allocated.

The full table of jumps for the first seventy elements:

len:   0   1   5   9  17  25  33  41  53  65
bytes: 56  88 120 184 248 312 376 472 568 664

You can see the spare room growing in proportion to the size — that is the 1.125 multiplier from consequence 1.

The price of indirection. Traversing a list of objects means, for each element: read a pointer from the array, follow it into the heap, read the object's header, fetch the value. Four memory accesses instead of one, with the objects scattered over the heap and almost certainly in different cache lines. Traversing a numpy array is a sequential read of adjacent bytes, which the processor predicts and loads ahead of time.

Hence a practical rule of thumb: the gap between a list and a buffer is the larger, the more data there is and the simpler the operation. On complex per-element logic the difference flattens out, because the logic itself dominates; on a simple sum it is at its maximum.

L3Where this is in the CPython sourceslistobject.c: list_resize and ins1, tupleobject.c, deque

Tag v3.11.15.

  • Objects/listobject.c, function list_resize — the growth formula is written there literally: new_allocated = ((size_t)newsize + (newsize >> 3) + 6) & ~(size_t)3. One line from which consequence 1 is derived.
  • Objects/listobject.c, ins1 — insertion with a shift through memmove. Consequence 2 as code.
  • Objects/tupleobject.c — the layout of a tuple and the free lists for small sizes.
  • Modules/_collectionsmodule.c — deque as a doubly linked list of fixed-size blocks; interestingly, a block holds several elements at once so as not to pay for a node per element.
connectionsWhere this leadsL01, L02, L05, L10 · the contrast with vector and deque

Connections

root R1 · Everything is an object, a name is a reference
← foundation L01 · Name, object, reference — why a container stores references and a slice copies shallowly
← foundation L02 · Numbers and strings — where the 28 bytes per integer in consequence 5 come from
→ next L05 · dict and hashability — how the thing that makes in constant-time is built
→ next L10 · Cycles, the collector and memory — why a freed list does not return memory to the system
↔ contrast std::vector<int> and Go slices: values in place versus pointers
↔ contrast deque versus a list: O(1) at both ends at the price of indexed access
readingFurther readingTime Complexity 🟧 · array 🟦 · list_resize 🟥

Further reading

Written by · The Python Canon