Sub topic 14
How much list operations cost
This chapter covers what common list operations cost as a list grows, and which patterns turn a fast program into a slow one. It assumes you know the list methods from earlier chapters (append, insert, pop, remove, sort, slicing), can write for loops, and have run Python scripts or used the REPL.
How a list is stored
A CPython list is a dynamic array: one block of memory holding a row of references, each pointing to an object. Three facts follow from this layout.
- Reading or replacing
items[i]jumps straight to sloti. The cost does not depend on the list's length. - Adding or removing at the end only touches the last slot.
- Adding or removing anywhere else shifts every item after that position by one slot.
"Cost" here means how the running time grows with the number of items n. Big-O notation describes that growth. O(1) means constant time, O(n) means time proportional to n, and O(n log n) is a little worse than linear. Big-O ignores constant factors, so it tells you how an operation scales, not how many nanoseconds it takes.
The cost table
| Operation | Cost | Why |
|---|---|---|
| `len(items)`, `items[i]`, `items[i] = x` | O(1) | Direct slot access |
| `items.append(x)` | O(1) amortized | Occasional resize, see below |
| `items.pop()` | O(1) | Removes the last slot |
| `items.insert(i, x)` | O(n - i) | Shifts later items right |
| `items.pop(i)`, `del items[i]` | O(n - i) | Shifts later items left |
| `items.remove(x)` | O(n) | Searches, then shifts |
| `x in items`, `items.index(x)`, `items.count(x)` | O(n) | Compares item by item |
| `items.extend(other)` | O(k) | k is the length of `other` |
| `items[a:b]`, `items.copy()` | O(b - a), O(n) | Builds a new list |
| `items.sort()`, `sorted(items)` | O(n log n) | Timsort |
| `items.reverse()` | O(n) | Swaps slots in place |
| `items.clear()` | O(n) | Releases each reference |
| `min(items)`, `max(items)`, `sum(items)` | O(n) | Visits every item |
Worst-case entries like insert(i, x) depend on position. Inserting near the end is cheap, and inserting at index 0 is the most expensive case.
Why append is "amortized" O(1)
A list keeps some spare capacity. When append finds the array full, it allocates a larger block (growing by roughly an eighth of the current size, plus a small constant) and copies the references over. That single append costs O(n). Because each resize buys room for many future appends, the total cost of n appends is still O(n), which averages to constant time per append. This averaging is what "amortized" means.
You can watch the over-allocation with sys.getsizeof. The size reported jumps only occasionally, not on every append.
import sys
items = []
last = sys.getsizeof(items)
print(0, last)
for i in range(20):
items.append(i)
size = sys.getsizeof(items)
if size != last:
print(len(items), size)
last = sizeThe exact byte counts differ between Python versions and platforms, but the pattern is the same: a few jumps for 20 appends.
Operations at the front are the expensive ones
insert(0, x) and pop(0) move every other item. On a list of one million items, each call shifts a million references. Doing that once is fine, but doing it in a loop is quadratic: n operations of O(n) each gives O(n²) total.
You can measure the difference with timeit. The setup string runs once, and each statement pair leaves the list at its original length.
from timeit import timeit
setup = "items = list(range(100_000))"
end = timeit("items.append(1); items.pop()", setup, number=1000)
front = timeit("items.insert(0, 1); items.pop(0)", setup, number=1000)
print(f"end: {end:.4f} s")
print(f"front: {front:.4f} s")The front version is typically orders of magnitude slower. Run it with 100_000 changed to 1_000_000 and the gap widens, because the end version stays flat while the front version grows with the list.
Searching is a linear scan
x in items, index and count have no shortcut. They compare x to each item with == (after an identity check) until they find a match. in and index stop at the first match, so a hit near the front is fast. A miss always scans the whole list. count always scans the whole list.
If you test membership repeatedly on a large collection, a list is the wrong container. A set uses hashing and answers in in O(1) on average.
from timeit import timeit
setup = "items = list(range(100_000)); lookup = set(items)"
print(timeit("99_999 in items", setup, number=1000))
print(timeit("99_999 in lookup", setup, number=1000))Building the set costs O(n) once, so it pays off when you do more than a handful of lookups. A set drops duplicates and order, so use it only when you do not need those.
Copies and slices cost memory and time
Every slice builds a new list, so items[1:] on a large list copies almost all of it. A loop that repeatedly takes items = items[1:] is quadratic for the same reason pop(0) is. A shallow copy (items.copy(), items[:], list(items)) is O(n) because it copies n references. It does not copy the objects they point to, which is why it is cheap per item. A deep copy with copy.deepcopy duplicates every nested object and costs much more.
Building a list: three ways, very different costs
The + operator on lists creates a new list each time. Using it to grow a list in a loop copies the whole list on every pass.
from timeit import timeit
def build_slow(n):
result = []
for i in range(n):
result = result + [i] # new list each time: O(n) per step
return result
def build_append(n):
result = []
for i in range(n):
result.append(i) # O(1) amortized
return result
def build_comprehension(n):
return [i for i in range(n)]
assert build_slow(1000) == build_append(1000) == build_comprehension(1000)
for fn in (build_slow, build_append, build_comprehension):
print(fn.__name__, round(timeit(lambda: fn(20_000), number=3), 4))build_slow is quadratic. The other two are linear, and the comprehension is usually the fastest because it avoids a method lookup and call on each iteration.
The augmented form result += [i] behaves differently from result = result + [i]. It calls extend and changes the list in place, so it stays linear. The two lines look nearly identical but have different costs.
Sorting cost
Python's sort is Timsort, which runs in O(n log n) in the worst case and does fewer comparisons on data that already contains ordered runs. A list that is nearly sorted sorts in close to O(n). Two practical points:
sorted(items)allocates a new list, so it needs O(n) extra memory.items.sort()works in place and needs little extra memory (it can use up to about n/2 temporary slots for merging).- The
keyfunction is called once per item, not once per comparison. An expensive key such as a regular expression match costsncalls, and Python caches the results while sorting.
Sorting inside a loop is a common hidden cost. If you only need the smallest item, min(items) is O(n) and cheaper than sorted(items)[0]. If you need the k smallest, heapq.nsmallest(k, items) avoids a full sort.
deque for queues
collections.deque is a doubly linked structure of blocks, designed so that adding and removing at either end is O(1). The trade-off is that indexing into the middle is O(n). Use it when you remove from the front, as in a queue. The next chapter covers stacks and queues in detail.
from collections import deque
from timeit import timeit
setup_list = "items = list(range(100_000))"
setup_deque = "from collections import deque; items = deque(range(100_000))"
print(timeit("items.append(1); items.pop(0)", setup_list, number=1000))
print(timeit("items.append(1); items.popleft()", setup_deque, number=1000))Measure before you optimize
Big-O predicts how time grows. It does not predict which version is faster for a list of 20 items, where constant factors dominate. A list of a few hundred items makes insert(0, x) or x in items perfectly acceptable. Switch containers when the data is large or the operation sits in a hot loop, and confirm with timeit before rewriting working code.
Exercise
This function removes every occurrence of a value from a list by repeatedly calling items.remove(value) while value in items. On a list of n items where all items equal value, what is the approximate total cost, and how would you rewrite it to run in O(n)?
Show answer
Each value in items check and each remove(value) is O(n) and the loop runs n times, so the total is O(n²). Rewrite it to build a new list in one pass: items = [x for x in items if x != value]. This visits each item once, so it is O(n). If you need to change the original list object in place, use the slice assignment items[:] = [x for x in items if x != value].
Exercise
You process a stream of tasks. You append new tasks to the end and take the oldest task from the front, and the backlog can reach millions of items. Which container should you use, and why is list.pop(0) a poor choice?
Show answer
Use collections.deque with append and popleft, which are both O(1). list.pop(0) shifts every remaining reference one slot left, so each call costs O(n) and processing the whole backlog costs O(n²).