Amortized Analysis

A Python list keeps its items in 1 contiguous block of memory slots, usually with a few spare slots at the end. When append finds every slot taken, the list cannot grow where it sits: it allocates a larger block, copies every existing reference into it, and frees the old one. That call costs O(n). Building a 10-million-row list with append in a loop still takes linear total time, and the reason is the size of the new block.

Charging each append in advance

Picture an array that doubles its capacity whenever it fills. Starting from 1 slot, 6 appends trigger resizes at the 2nd, 3rd and 5th append, and each resize copies only the items already stored.

slots = [None]
size = 0
copies = 0
for item in ["a", "b", "c", "d", "e", "f"]:
    if size == len(slots):
        bigger = [None] * (len(slots) * 2)
        for i in range(size):
            bigger[i] = slots[i]
            copies += 1
        slots = bigger
        print("resized to", len(slots), "slots, copies so far:", copies)
    slots[size] = item
    size += 1
print(slots)
print("appends:", size, "copies:", copies)
resized to 2 slots, copies so far: 1
resized to 4 slots, copies so far: 3
resized to 8 slots, copies so far: 7
['a', 'b', 'c', 'd', 'e', 'f', None, None]
appends: 6 copies: 7

Amortized analysis bounds the total cost of a whole sequence of operations, then divides by the number of operations. Charge every append 3 units: 1 pays for writing its own slot and 2 go into savings. When an array of capacity 2k fills up, the k items appended since the previous resize have saved 2k units, exactly the price of copying all 2k items. The savings never run out, so n appends cost at most 3n units. Each append is amortized O(1), even though the few that resize cost O(n) on their own.

The growth rule decides the total

The savings argument needs growth proportional to the current size. The program below counts copies under doubling and under a rule that adds a fixed 10 slots per resize, then prints copies per append for 3 list sizes.

def append_cost(n, grow):
    capacity, size, copies = 1, 0, 0
    for _ in range(n):
        if size == capacity:
            copies += size
            capacity = grow(capacity)
        size += 1
    return copies

for n in [1_000, 10_000, 100_000]:
    doubling = append_cost(n, lambda c: c * 2)
    plus_ten = append_cost(n, lambda c: c + 10)
    print(n, round(doubling / n, 2), round(plus_ten / n, 1))

Output:

1000 1.02 49.6
10000 1.64 499.6
100000 1.31 4999.6

Doubling stays between 1 and 2 copies per append at every size. The fixed step makes the cost per append climb with n: each resize copies the whole array but buys room for only 10 more appends, so n appends trigger about n/10 resizes averaging n/2 copies each, O(n²) in total. At 100,000 appends that is 4,999.6 copies per append against 1.31.

CPython's own list_resize in Objects/listobject.c grows a full list by about one eighth of its size plus a few slots. That smaller factor copies each item about 8 times over a long run in exchange for less idle memory, and because growth is still proportional to size, append stays amortized O(1).

Where the guarantee stops

A loop runs once for each of the n rows in rows. Which loop body makes the whole loop O(n²)?

About this lesson

This section is part of the Complexity: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.