Arrays and Dynamic Arrays: How a Python List Really Works
The array is the simplest data structure and the one every other structure is compared against. Knowing exactly what it makes cheap and what it makes expensive explains most of the performance surprises people hit with Python lists. Examples use Python 3.10 or later and only the standard library.
Contiguous memory and O(1) indexing
An array is a block of memory holding its items one after another, each slot the same size. If the block starts at address base and each slot takes s bytes, item i lives at base + i * s. Finding it is one multiplication and one addition, no matter how long the array is or which index you ask for. That is why reading or writing a[i] is O(1).
The same layout makes some operations expensive. To insert a new item at position 0, every existing item has to move one slot to the right to make room, which is n moves for an array of n items. Deleting from the front moves them all back. Searching for a value with no other information means looking at the items one by one, O(n) in the worst case.
Fixed-size arrays and dynamic arrays
A fixed-size array is allocated once with a set capacity. In languages such as C, you choose the size up front and cannot add a 101st item to a 100-slot array. That is fast and compact, but awkward when you do not know how many items are coming.
A dynamic array hides the fixed size behind a growing one. It keeps two numbers: the size (how many items are stored) and the capacity (how many slots are allocated). Appending writes into the next free slot while size is below capacity. When the block is full, the array allocates a larger block, copies every item across, frees the old block, and then appends.
A single append that triggers a resize costs O(n), because of the copy. The key design choice is to grow the capacity by a constant factor (for example doubling it) rather than by a fixed number of slots. Then resizes become rare as the array grows: after a copy of n items, the next n appends are cheap. Spread over a long run of appends, the copying adds only a constant amount per append, so append is amortized O(1): any sequence of n appends costs O(n) in total, even though an individual append can cost O(n).
The Amortized Analysis Calculator simulates exactly this. With a starting capacity of 1 and a growth factor of 2, 1,000 appends trigger 10 resizes, and the total cost (1,000 writes plus every copied item) is 2,023, an amortized cost of 2.02 per append. With a growth factor of 1.5 the same 1,000 appends take 16 resizes and cost 3,120 in total, 3.12 per append. Either way the cost per append stays a small constant as n grows. If instead the array grew by a fixed number of slots each time, the copies would add up to O(n^2) over n appends, and append would no longer be amortized O(1). The amortized analysis post works through the accounting.
A Python list is a dynamic array of references
A Python list is a dynamic array. Its slots do not hold the objects themselves; each slot holds a reference (a pointer) to an object stored elsewhere. That is how one list can hold an int, a string and another list side by side: every slot is the same size because every slot is just a reference.
You can watch the capacity grow with sys.getsizeof, which reports the size of the list object including its block of reference slots (not the objects they point to). This prints the size only when it changes:
import sys
print(sys.version.split()[0])
items = []
last = sys.getsizeof(items)
print(f"len 0: {last} bytes")
for i in range(1, 33):
items.append(i)
size = sys.getsizeof(items)
if size != last:
print(f"len {i:2}: {size} bytes")
last = size
3.12.13
len 0: 56 bytes
len 1: 88 bytes
len 5: 120 bytes
len 9: 184 bytes
len 17: 248 bytes
len 25: 312 bytes
This is one run on CPython 3.12.13, 64-bit. Each jump is a resize: the list allocates several spare slots at once, so the next few appends need no new memory. The exact sizes and step pattern are an implementation detail that can differ between Python versions and builds, so do not write code that depends on them. What matters is that the extra room grows with the size of the list, which is what keeps append amortized O(1).
The cost of each list operation
| Operation | Example | Time | Why |
|---|---|---|---|
| Index or assign | a[i], a[i] = x | O(1) | Address arithmetic |
| Append | a.append(x) | Amortized O(1) | Occasional resize copies everything |
| Pop from the end | a.pop() | O(1) | Nothing else moves |
| Insert or pop at the front | a.insert(0, x), a.pop(0) | O(n) | Every item shifts one slot |
| Insert or pop at index i | a.insert(i, x), a.pop(i) | O(n - i) | Items after i shift |
| Membership | x in a | O(n) | Linear scan |
| Length | len(a) | O(1) | The size is stored |
| Slice copy | a[i:j] | O(j - i) | Copies that many references |
The same operations in code:
scores = [70, 85, 90]
print(scores[1]) # index: O(1)
scores[1] = 88 # assign: O(1)
scores.append(95) # append at the end: amortized O(1)
last = scores.pop() # pop from the end: O(1)
scores.insert(0, 60) # insert at the front: O(n), every item shifts right
first = scores.pop(0) # pop from the front: O(n), every item shifts left
print(scores, last, first)
print(88 in scores) # membership: O(n), a linear scan
85
[70, 88, 90] 95 60
True
The two lines to watch are insert(0, x) and pop(0). Each one looks as harmless as append, but called inside a loop over n items they turn an O(n) algorithm into an O(n^2) one. If you need to add or remove at the front repeatedly, use collections.deque, which does both ends in O(1), or build the list in reverse and flip it once at the end. Repeated x in a checks on a large list have the same problem; a set answers membership in O(1) on average.
For large amounts of numeric data, the standard library's array module stores raw machine values (for example 8-byte floats) directly in the block instead of references to separate objects, which uses much less memory; it is still a dynamic array with the same costs.
Two-dimensional lists and the aliasing bug
A grid in Python is usually a list of rows, each row a list. The tempting shortcut [[0] * 3] * 2 is wrong: the outer * 2 copies the reference to one row, so both rows are the same object.
grid = [[0] * 3] * 2 # two references to ONE row
grid[0][0] = 1
print(grid)
grid = [[0] * 3 for _ in range(2)] # two separate rows
grid[0][0] = 1
print(grid)
[[1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0]]
Setting one cell in the first version changed both rows. The list comprehension runs [0] * 3 once per row, so each row is a separate list. The inner [0] * 3 is safe because integers are immutable: replacing row[0] rebinds that slot without touching the others. This and other easy-to-miss mistakes are collected in common bugs in algorithm code.
When an array is the wrong choice
Arrays win when you index by position, scan in order, or add and remove at the end, which covers most everyday code. Their contiguous layout is also friendly to the processor cache, because reading one item brings its neighbors into fast memory. They lose when you insert or delete in the middle or at the front over and over, or when you need fast lookup by value. For the first case, compare linked lists, which insert at a known node in O(1) but give up O(1) indexing; for the second, a hash-based set or dict.
Check yourself
- A loop calls
result.insert(0, x)for each of n items. What is the total cost, and how would you make it O(n)? (O(n^2); append each item and reverse once at the end, or use adequewithappendleft.) - Why is a single
appendsometimes O(n), yet append is still called O(1)? (A resize copies every item, but with growth by a constant factor the copies average out to a constant per append over any sequence of appends.) - What does
sys.getsizeofon a list measure? (The list object and its reference slots, not the objects the references point to.)