Dynamic arrays: how append stays fast
🌍 In real life. Your books fill a small cupboard. When it's full you buy a bigger one, carry every book across, and then keep adding. Moving is hard work, but you don't move house for every new book: the new cupboard has spare shelves, so the next many books just go in.
An array's block often can't grow in place (the memory after it may be in use). So how does items.append(x) keep adding forever, and why is it still fast?
The idea in one sentence: a dynamic array keeps spare room at the end; when that runs out it moves to a block that is a good deal bigger, so moves happen rarely and their cost, spread over all the appends, stays small.
Its words:
- dynamic array: an array that grows by itself as items are added; Python's list is one
- length and capacity: how many items are stored, and how many places the block has
- amortised cost: the cost of an operation averaged over a long run of them, so the rare slow ones are shared out among the many fast ones
How it works, step by step:
- the list has a length (items stored) and a capacity (places in its block)
- if length < capacity, append writes into the next free place: 1 step
- if the block is full, Python gets a bigger block, copies every item across, then writes the new one
- CPython grows by about one eighth plus a little (4, 8, 16, 24, 32, 40, 52, …); a textbook dynamic array doubles. Either way each move gives room for many more appends
Watch nine appends: the block grows twice, and the copy counter jumps only then.
What it costs: amortised O(1). One append that moves the block costs O(n), but it can't happen again for a long time. Add up all the work and share it out. With doubling, each move copies twice as many items as the move before it. The last move copies fewer than n items, and all the earlier moves together copy fewer than that again (1 + 2 + 4 + … is always less than the next number up), so n appends make fewer than 2n copies: with the n writes, under 3 steps per append, whatever n is. Spreading the rare big cost over the many cheap ones is called amortised cost: append is amortised O(1), even though one append now and then is slow.
Why grow by a lot, not by 1? If the block grew by just one place each time, every append would copy everything: 1 + 2 + … + n is about n²/2 copies, O(n²) in total. Growing in big steps is what makes the trick work.
import struct, sys
SLOT = struct.calcsize("P") # bytes for one place in the block
EMPTY = sys.getsizeof([])
items = []
last = None
for x in range(1, 41):
items.append(x)
capacity = (sys.getsizeof(items) - EMPTY) // SLOT
if capacity != last:
print("length", len(items), "-> room for", capacity)
last = capacityMistakes and edge cases. "Amortised O(1)" doesn't mean every append is fast: the one that moves the block copies everything, which is why a list that must never pause (a game frame, a sound buffer) is often made at full size up front, like [0] * 1000. And len(items) is the length, not the capacity: Python never shows the spare room except through sys.getsizeof.
Quiz
A list has length 4 and capacity 4. What happens on the next append?
- A bigger block is made and all 4 items are copied, then the new one is added
- The new item overwrites the last one
- Python raises an error: the list is full
A doubling array starts with capacity 1. How many items does it copy in total while appending 8 items? What does this print?
capacity, length, copies = 1, 0, 0 for x in range(8): if length == capacity: copies += length capacity *= 2 length += 1 print(copies, capacity)What does "append is amortised O(1)" mean?
- Averaged over many appends, each costs a constant amount, though an occasional one is slow
- Every single append takes exactly one step
- append never copies anything
If a dynamic array grew by exactly one place every time it was full, what would n appends cost in total?
- O(n²): every append would copy everything
- O(n)
- O(log n)
What does this print?
items = [] for x in range(5): items.append(x * x) print(len(items), items[-1])This array should grow its block when it is full, but the second append stops with IndexError: list assignment index out of range. Which line is wrong?
class Doubling: def __init__(self): self.cap, self.n, self.block = 1, 0, [None] def append(self, x): if self.n == self.cap: self.cap * 2 new = [None] * self.cap new[:self.n] = self.block[:self.n] self.block = new self.block[self.n] = x self.n += 1
Coding tasks
Write
copies_for(n): a doubling array starts with capacity 1; when it is full it doubles and copies every item. How many copies donappends make in total?Build a dynamic array: finish the class
Shelf. It keeps its items inself.block, a Python list of fixed sizeself.capacity(starting at 1, filled withNone).append(x)putsxin the next free place; whenself.blockis full it makes a new block twice as big, copies the items across (counting each one inself.copies), then addsx.get(i)gives back itemi, andlen()the number of items.