Sub topic 3
Arrays and dynamic lists: fast indexing, costly middle edits
This chapter assumes you know basic Python, loops and functions, and have a rough idea of what Big-O notation means. It covers the structure behind Python's list and explains which operations it makes cheap and which it makes expensive.
The working model
A dynamic list stores its items in one contiguous block of memory. Python's list holds references (pointers) to objects, and each reference takes the same amount of space. Because of this, the interpreter can compute the address of item i directly, without visiting the items before it.
That gives the central trade-off:
- Reading or writing
items[i]is O(1). - Adding or removing at the end is O(1) amortized.
- Inserting or removing at the front or middle is O(n), because every later item must shift by one slot.
- Searching an unsorted list with
inor.index()is O(n).
"Amortized" means the cost is averaged over many operations. A list reserves spare capacity, so most appends just fill a free slot. When the block is full, the list allocates a larger block and copies the references over. That single append is O(n), but it happens rarely enough that the average stays constant.
Measuring the difference
You can see the cost of middle edits by timing front insertion against appending.
import time
def time_it(action, n):
items = []
start = time.perf_counter()
for i in range(n):
action(items, i)
return time.perf_counter() - start
n = 50_000
append_time = time_it(lambda items, i: items.append(i), n)
insert_time = time_it(lambda items, i: items.insert(0, i), n)
print(f"append: {append_time:.4f} s")
print(f"insert(0): {insert_time:.4f} s")Exact numbers depend on your machine. The insert(0, ...) loop does O(n) work per call, so its total grows roughly with n squared. Doubling n makes the front-insert loop about four times slower, but only about twice as slow for appends.
When a list is the right choice
Choose a list when your problem looks like this:
- You read items by position, often.
- You build a sequence by appending, then iterate over it.
- You need to keep insertion order.
- You sort once and then read many times.
Lists also iterate quickly, because neighboring items sit next to each other in memory. Chapter 12 returns to this effect.
Common errors
- Removing from the front in a loop.
items.pop(0)anddel items[0]are O(n). Draining a list this way costs O(n²) overall. Usecollections.dequewithpopleft()when you need queue behavior. - Using
inon a large list repeatedly. Each check scans the list. If you test membership many times, build a set once. - Building a list with repeated concatenation.
result = result + [x]creates a new list each time. Useresult.append(x)instead. - Deleting while iterating. Removing items shifts the indexes under the loop, so some items are skipped. Build a new list with a comprehension instead.
numbers = [1, 2, 3, 4, 5, 6]
# Risky: modifies the list while looping over it
for n in numbers:
if n % 2 == 0:
numbers.remove(n)
print(numbers) # [1, 3, 5] here, but skipped items are common with other data
# Safer: build a new list
numbers = [1, 2, 3, 4, 5, 6]
numbers = [n for n in numbers if n % 2 != 0]
print(numbers) # [1, 3, 5]Summary of costs
| Operation | Cost | Note |
|---|---|---|
| `items[i]` | O(1) | Direct address computation |
| `append(x)` | O(1) amortized | Occasional resize |
| `pop()` from end | O(1) | |
| `insert(i, x)` | O(n) | Shifts later items |
| `pop(0)` | O(n) | Shifts all items |
| `x in items` | O(n) | Linear scan |
Exercise
A program reads tasks from a list and processes them in arrival order using task = tasks.pop(0) inside a loop over 200,000 tasks. Why is this slow, and what would you change?
Show answer
Each pop(0) removes the first item and shifts all remaining references left by one slot, so it costs O(n). Over 200,000 tasks the total is O(n²). Replace the list with collections.deque and call popleft(), which is O(1), or iterate over the list by index or with a plain for loop if you do not need to modify it.