Python List Internals
What you will learn
- How a list is stored: a row of references, with spare room for growth
- Which operations are fast and which are slow, in big-O terms
- Why a list holds references, not the objects themselves
- How
sortworks, and why it is stable - When to choose a set, deque, tuple or array instead
You do not need this lesson to use lists, but it explains why some operations are quick and others slow, which helps you write programs that stay fast as the data grows.
1. A list is a row of references
Inside, a Python list is a row of slots in memory. Each slot does not hold the item itself, but a reference to it (the address of the object, lesson 2.7). The list also remembers its length and how many slots it has.
list: [ ref ][ ref ][ ref ][ ref ] (spare)
| | | |
v v v v
10 "a" [1, 2] 3.5 <- the objects live elsewhere
Three consequences follow:
- Items can be of any type and any size: every slot is the same size, because it holds only a reference.
- Reading by index is instant: Python computes the slot's position from the index, and does not search.
- Different positions can point to the same object, which is why
[inner] * 3repeats one inner list three times (lesson 7.5):
inner = [0]
outer = [inner] * 3
print(id(outer[0]) == id(outer[1]) == id(outer[2]))
True
(id() shows an object's identity, lesson 2.6.)
Quick check: does `[[1, 2], [3]]` store the numbers inside the outer list?
No. The outer list stores two references, one to each inner list, and those lists store references to the numbers.
2. Spare room: how a list grows
If a list had exactly as many slots as items, every append would have to build a bigger row and copy everything. Instead, Python over-allocates: when it must grow, it gets extra spare slots, so the next several appends need no copying.
You can watch the size with sys.getsizeof, which reports the size of the list object (its row of slots, not the items). Here are the results on one computer (Python 3.13.7, 64-bit Windows; the numbers may differ on other versions and systems):
import sys
sizes = []
data = []
last = -1
for i in range(40):
size = sys.getsizeof(data)
if size != last:
sizes.append((len(data), size))
last = size
data.append(i)
print(sizes)
[(0, 56), (1, 88), (5, 120), (9, 184), (17, 248), (25, 312), (33, 376)]
Read each pair as (number of items, size in bytes):
| At item count | Size in bytes | Meaning |
|---|---|---|
| 0 | 56 | an empty list |
| 1 | 88 | room for 4 items arrived at once (32 more bytes = 4 slots of 8 bytes) |
| 5 | 120 | now room for 8 |
| 9 | 184 | now room for 16 |
| 17 | 248 | room for 24 |
The size jumps only now and then, and between jumps the appends are free. Because the growth is proportional, the average cost of an append stays small however long the list gets. This is called amortised constant time.
3. Fast and slow operations
Big-O notation describes how the time grows with the number of items n:
| Notation | Meaning | Example |
|---|---|---|
| O(1) | the same time however big the list | reading lst[i] |
| O(n) | time grows in proportion to n |
x in lst |
For lists:
| Operation | Cost | Why |
|---|---|---|
lst[i], lst[i] = v |
O(1) | direct slot lookup |
lst.append(x), lst.pop() |
O(1) (amortised) | work at the end only |
len(lst) |
O(1) | the length is stored |
x in lst, lst.index(x), lst.count(x) |
O(n) | look at items one by one |
lst.insert(0, x), lst.pop(0), lst.remove(x) |
O(n) | items must be shifted |
lst[a:b], lst.copy() |
O(k) | copies k references |
lst.sort() |
O(n log n) | see section 5 |
A quick test on one computer shows the pattern. (Times will differ on yours; look at the ratios.)
| Operation | List of 10,000 | List of 100,000 |
|---|---|---|
| read the middle item (20,000 times) | 1.39 ms | 1.32 ms |
-1 in lst (200 times) |
11.6 ms | 139 ms |
insert(0, x) (200 times) |
0.7 ms | 7.0 ms |
Reading by index took the same time for both sizes. The membership test took about 12 times longer for a list 10 times longer, and the insert at the front about 10 times longer. That is "O(1) versus O(n)" in practice. Measure your own code with timeit (lesson 18.5) before you optimise.
4. Choosing something else
When one of the slow operations is your main job, pick a different structure:
| You need | Better choice | Why |
|---|---|---|
| fast "is it in there?" | set or dict |
a hash lookup takes the same time however big (chapters 9 and 10) |
| fast work at both ends | collections.deque |
lesson 7.6 |
| a fixed collection that must not change | tuple |
immutable and a little smaller (chapter 8) |
| a long row of one kind of number | array.array |
stores raw numbers, not references |
| a sorted list with fast search and insert | bisect (lesson 7.4) |
halves the range each step |
A set stays fast as it grows. In the test, a membership test in a set of 100,000 numbers took about the same time as in a set of 10,000 (a ratio near 1).
Lists against arrays
array.array stores one type as raw values, so it is much more compact:
import array
import sys
arr = array.array("i", range(1000))
print(sys.getsizeof(arr), sys.getsizeof(list(range(1000))))
4200 8056
("i" means a C integer.) The list is nearly twice as large here, and that is only the row of references: each number is its own object as well. An array rejects other types: arr.append("x") raises TypeError: 'str' object cannot be interpreted as an integer. For heavy numeric work, the third-party NumPy library goes much further (a separate course).
5. How sorting works
sort() and sorted() use an algorithm called Timsort. According to the Python documentation:
- It is stable: items with equal keys keep their original order (lesson 7.4).
- It takes advantage of order already present in the data, so an almost-sorted list sorts very quickly.
- It takes O(n log n) time in general: for a million items, roughly twenty million comparisons, not a trillion.
list.sort() changes the list in place and returns None, and sorted() builds a new list (lesson 7.4).
6. Memory and sharing
- A list's row of references is small (8 bytes per slot on a 64-bit system). The objects are extra:
sys.getsizeofon a list does not include them. - Slices and
.copy()copy the references, not the objects, which is why they are shallow (lesson 7.5). [0] * 1_000_000makes a million slots all pointing at the same0object, so it is cheap in memory.
big = [0] * 10**6
print(len(big), sys.getsizeof(big) // 10**6)
1000000 8
That is about 8 bytes per slot: 8 MB for a million references, and no copies of the 0.
Worked example: remove duplicates fast
Remove the repeated values from a list while keeping the first occurrence of each, and see why a set makes it fast.
data = [3, 1, 3, 2, 1, 4, 2]
slow = []
for v in data:
if v not in slow: # list search: O(n) each time
slow.append(v)
seen = set()
fast = []
for v in data:
if v not in seen: # set lookup: about O(1)
seen.add(v)
fast.append(v)
print(slow, fast, slow == fast)
print(list(dict.fromkeys(data)))
[3, 1, 2, 4] [3, 1, 2, 4] True
[3, 1, 2, 4]
| Version | Cost per test | For n items |
|---|---|---|
v not in slow (a list) |
O(n) | about n × n steps in all |
v not in seen (a set) |
about O(1) | about n steps in all |
For seven items you cannot tell the difference. For a million items the list version can take a very long time, and the set version stays quick. dict.fromkeys does the same in one line, because a dictionary keeps order and has no duplicate keys (chapter 9). The values are made up.
Common mistakes
- Using
x in listin a big loop instead of a set. - Using
pop(0)orinsert(0, x)repeatedly on a long list. - Optimising before measuring. Use
timeit, and only improve what is actually slow. - Believing
sys.getsizeof(lst)includes the items. It counts only the list's own row. - Treating the exact byte sizes as fixed. They change between Python versions.
Key takeaways
- A list is a row of references with spare room, so appending is cheap on average.
- Index,
append,pop()andlenare O(1);in,index,count,insert(0, x),pop(0)andremoveare O(n). - Sets and dictionaries answer "is it in there?" in about O(1); deques are quick at both ends.
- Slices and copies copy references, not objects, so they are shallow.
sortis Timsort: stable, fast on nearly-ordered data and O(n log n) in general.
Practice
1. What does a list actually store in each slot?
Show answer
A reference to an object, not the object itself.
2. Why is lst.append(x) fast on average even though the list sometimes has to grow?
Show answer
When it grows, Python allocates spare slots, so the next several appends need no copying. The occasional expensive step is spread over many cheap ones (amortised constant time).
3. Which is faster for a large collection: x in my_list or x in my_set? Why?
Show answer
x in my_set. A set finds an item by its hash in about constant time, while a list looks at the items one by one.
4. Why is pop(0) on a long list slow?
Show answer
Every remaining item has to shift one place to the left to fill the gap, which takes time proportional to the list length.
5. Does sys.getsizeof([[1, 2, 3]]) include the memory of the numbers?
Show answer
No. It counts only the outer list's own row of references, not the inner list or the numbers.
6. Name two structures better than a list for a first-in-first-out waiting line, and for fast membership tests.
Show answer
A collections.deque for the waiting line, and a set (or a dict) for membership tests.