Sub topic 14
How much list operations cost
This chapter assumes you know how to create lists, index them, and use append, insert, pop, remove and in. It explains why some of those operations stay fast as a list grows and others slow down.
Why cost matters
A list is stored as a block of references, one after another, in memory. Python can jump straight to any position in that block. It cannot insert or remove at the front without moving every item after that position.
Cost is written in big-O notation. O(1) means the time does not depend on the list length. O(n) means the time grows in proportion to the length n.
Cost table
| Operation | Cost | Why |
|---|---|---|
| `lst[i]`, `lst[i] = x`, `len(lst)` | O(1) | Direct jump to a position |
| `lst.append(x)` | O(1) amortized | Usually writes one slot. Occasionally the list resizes |
| `lst.pop()` | O(1) | Removes the last slot |
| `lst.pop(0)`, `lst.insert(0, x)` | O(n) | Every other item shifts one place |
| `del lst[i]`, `lst.insert(i, x)` | O(n - i) | Items after `i` shift |
| `lst.remove(x)`, `lst.index(x)`, `lst.count(x)`, `x in lst` | O(n) | Scans from the start, comparing each item |
| `lst[a:b]`, `lst.copy()` | O(k) | Copies `k` references |
| `lst.extend(other)` | O(k) | Adds `k` items |
| `lst.sort()`, `sorted(lst)` | O(n log n) | Comparison sort |
"Amortized" means averaged over many calls. A single append can be slow when Python grows the underlying block, but it grows it by extra room each time, so the average stays constant.
Measuring the difference
The timeit module runs a statement many times and reports the total seconds. Each statement below keeps the list the same length, so every run does equal work.
from timeit import timeit
n = 20_000
setup = f"data = list(range({n}))"
print("pop() from end:", timeit("data.append(data.pop())", setup, number=1000))
print("pop(0) from front:", timeit("data.append(data.pop(0))", setup, number=1000))
print("in, item at end:", timeit(f"{n - 1} in data", setup, number=1000))
print("in, item at start:", timeit("0 in data", setup, number=1000))The exact times depend on your machine. The pattern does not. Working at the front is far slower than working at the end. Searching for the last item is far slower than finding the first one, because the scan stops at the first match.
Costs that hide inside loops
A single O(n) call is fine. The trouble comes when you repeat it inside a loop, because the costs multiply. This function checks every item against a list:
def common(a, b):
return [x for x in a if x in b] # each "in" scans b: O(len(a) * len(b))If both lists hold 100,000 items, that is up to ten billion comparisons. Converting b to a set first makes each membership test O(1) on average:
def common_fast(a, b):
b_set = set(b) # one O(len(b)) pass
return [x for x in a if x in b_set]
print(common_fast([1, 2, 3, 4], [3, 4, 5])) # [3, 4]A set does not keep order or duplicates in b, but a still drives the output, so the result order is unchanged.
Other loop traps:
- Building a string or list with
result = result + [x]copies the whole list each time. Useresult.append(x). - Calling
lst.remove(x)in a loop is O(n) per call. Build a filtered list with a comprehension instead. - Calling
lst.count(x)for every distinct value rescans the list each time.
If you need fast removal from the front, the next chapter shows collections.deque.
Exercise
A script reads 200,000 lines into a list, then runs while lines: process(lines.pop(0)). It is slow. Why, and what is the smallest change that fixes it?
Show answer
pop(0) shifts every remaining item left by one place, so each call is O(n) and the whole loop is O(n squared). The smallest fix is to reverse the list once with lines.reverse() and call lines.pop(), which removes from the end in O(1). Alternatively, loop with for line in lines: if the list does not need to be emptied.