Sub topic 8
deque versus list: where each is fast
This chapter assumes you know the basic list operations (append, pop, insert, indexing, slicing) and the deque methods from the earlier chapters (append, appendleft, pop, popleft). It also assumes you have read the idea of Big-O notation, which describes how the cost of an operation grows with the size of the data. Here, O(1) means the cost stays about the same, and O(n) means the cost grows in proportion to the number of items.
Two different memory layouts
A list is a dynamic array. It stores references to its items in one contiguous block of memory. That layout makes items[i] a direct jump to a known position. It also means that removing or inserting at the front forces every other reference to shift by one slot.
A deque is built from a chain of fixed-size blocks that are linked in both directions. Python's implementation keeps pointers to the first and last block. Adding or removing at either end touches only an end block, so nothing else moves. The price is that reaching item i means walking block by block from the nearer end.
Each structure is fast where its layout helps and slow where it hurts.
| Operation | list | deque |
|---|---|---|
| `append(x)` / `pop()` at the right end | O(1) amortized | O(1) |
| `insert(0, x)` / `appendleft(x)` | O(n) | O(1) |
| `pop(0)` / `popleft()` | O(n) | O(1) |
| `items[i]` near the ends | O(1) | O(1) |
| `items[i]` in the middle | O(1) | O(n) |
| Slicing `items[a:b]` | Supported | Not supported |
| `x in items` | O(n) | O(n) |
"Amortized" means that an occasional append is slower because the list must grow its array, but the average cost over many appends is constant.
Measuring the front of the sequence
Using a list as a queue by calling pop(0) is a common mistake. It works, and it is fine for ten items. With many items, the cost adds up. The script below drains 100,000 items from each structure.
from collections import deque
from timeit import timeit
N = 100_000
def drain_list():
items = list(range(N))
while items:
items.pop(0)
def drain_deque():
items = deque(range(N))
while items:
items.popleft()
print("list.pop(0): ", timeit(drain_list, number=1))
print("deque.popleft: ", timeit(drain_deque, number=1))The exact times depend on your machine, but the list version is typically many times slower, and the gap widens as N grows. Doubling N roughly doubles the deque time and roughly quadruples the list time. The quadratic growth happens because each of the N pops shifts up to N references.
Measuring the middle of the sequence
The trade-off reverses for random access. The next script reads one item from the middle of a million-item sequence.
from collections import deque
from timeit import timeit
N = 1_000_000
as_list = list(range(N))
as_deque = deque(as_list)
mid = N // 2
print("list[mid]: ", timeit(lambda: as_list[mid], number=1000))
print("deque[mid]: ", timeit(lambda: as_deque[mid], number=1000))The list lookup stays constant. The deque lookup has to walk about half of the blocks, so it is noticeably slower. Indexing at position 0 or -1 is fast on both, because those are the ends.
No slicing on a deque
A list supports items[1:4]. A deque raises a TypeError for that syntax, because slicing would need the same middle access that deques make slow. When you need a window of items, use itertools.islice, which walks from the left and stops early.
from collections import deque
from itertools import islice
d = deque(range(10))
try:
d[1:4]
except TypeError as error:
print("TypeError:", error)
print(list(islice(d, 1, 4))) # [1, 2, 3]
print(list(d)[-3:]) # [7, 8, 9]islice still has to walk past the first start items, so it is O(start + length). If you need frequent slices, a list is the better container.
What stays the same
Both containers have O(n) membership tests (x in items), remove, and count, because each has to scan items. Neither one is a good choice for repeated membership checks. Use a set or dict for that. Both also keep insertion order and allow duplicates.
A deque can also give you one more guarantee. Its append, appendleft, pop, and popleft methods are thread-safe, meaning they work correctly when several threads use them on the same deque at the same time. This is why deques are a common choice for simple work queues between threads. Compound steps such as "check length, then pop" are still not atomic, so they need a lock or a try/except IndexError.
Deciding between them
The decision depends on where your code touches the sequence.
Some practical rules follow from this:
- Use a
listfor stacks (push and pop at the right end), for sorting, for slicing, and for random access by position. - Use a
dequefor first-in, first-out queues, for sliding windows withmaxlen, and for any code that regularly works at the left end. - If a list is small (a few dozen items), the difference is too small to matter. Choose the one that makes the code clearer.
- If you are unsure, measure with
timeiton data of realistic size.
Exercise
A program stores 500,000 log lines in a list. It repeatedly removes the oldest line with lines.pop(0) and appends new lines at the end. Which container should replace the list, and what operation changes? Name one thing the program can no longer do directly with the new container.
Show answer
Use a deque, and replace lines.pop(0) with lines.popleft(), which is O(1) instead of O(n). The program can no longer slice the container directly (for example lines[10:20] raises TypeError), and indexing into the middle becomes O(n). It would need itertools.islice or a conversion to a list for those cases.