Sub topic 8
deque versus list: where each is fast
This chapter compares collections.deque and the built-in list operation by operation. You will learn where each type is fast, where it is slow, and how to decide between them with measurements instead of habit.
It assumes you can write basic Python loops and functions, use append and pop on a list, and index into one. It also assumes you have read the earlier chapters on deque in this tutorial: append, appendleft, pop, popleft, maxlen, and rotate.
Two different memory layouts
The speed differences come from how each type stores its items.
A list is a dynamic array. CPython keeps one contiguous block of memory that holds references to the items. Reaching item i is a single address calculation, which is why items[i] is O(1) wherever i is. The list over-allocates room at the end, so append is O(1) amortized. Occasionally an append has to allocate a larger block and copy every reference.
The cost sits at the front. Removing or inserting at index 0 has to shift every other reference by one slot. That is a memory move proportional to the length, so list.pop(0) and list.insert(0, x) are O(n).
A deque is a doubly linked list of fixed-size blocks. In CPython each block holds 64 item slots, and each block points to its neighbors. The deque tracks the first and last used positions, so adding or removing at either end touches only an end block. When a block fills or empties, the deque allocates or frees one block. No other item moves, so both ends are O(1).
The price is random access. To reach item i, the deque has to walk block by block from the nearer end. Indexing near either end is fast. Indexing near the middle is O(n), although the constant is small because the walk skips 64 items per hop.
The operation table
| Operation | `list` | `deque` |
|---|---|---|
| `append(x)` (right end) | O(1) amortized | O(1) |
| `pop()` (right end) | O(1) | O(1) |
| Insert at left end | O(n) with `insert(0, x)` | O(1) with `appendleft(x)` |
| Remove from left end | O(n) with `pop(0)` | O(1) with `popleft()` |
| `x[0]` or `x[-1]` | O(1) | O(1) |
| `x[i]` in the middle | O(1) | O(n) |
| Slice `x[a:b]` | Supported | Not supported |
| `insert(i, x)` in the middle | O(n) | O(n) |
| `remove(x)`, `x in seq`, `index(x)` | O(n) | O(n) |
| `len(x)` | O(1) | O(1) |
| Sort in place | `sort()` | No such method |
The table shows two opposite specializations. deque removes the cost of working at the left end and gives up cheap random access. list keeps cheap random access and pays for the left end.
Measuring the left-end gap
Complexity classes tell you how cost grows, not what it is for your sizes. Run this script to see the growth. It drains a container from the left, once with a list and once with a deque.
from collections import deque
from timeit import timeit
def drain_list(n):
items = list(range(n))
while items:
items.pop(0)
def drain_deque(n):
items = deque(range(n))
while items:
items.popleft()
for n in (1_000, 10_000, 50_000):
t_list = timeit(lambda: drain_list(n), number=1)
t_deque = timeit(lambda: drain_deque(n), number=1)
print(f"n={n:>6}: list.pop(0) {t_list:.4f}s deque.popleft {t_deque:.4f}s")Absolute times depend on your machine, so read the trend. Each time n grows tenfold, the deque time grows roughly tenfold, because the total work is n pops of constant cost. The list time grows roughly a hundredfold, because the total work is n pops that each shift up to n references.
The gap is small for small lists. Shifting 20 references is one fast memory move, and a plain list can beat a deque there because it has less bookkeeping. The deque wins clearly once a queue can hold thousands of items. If your queue never exceeds a few dozen items, either type works, and you can choose for readability.
Random access and slicing
Indexing a deque works, including negative indexes. Slicing does not.
from collections import deque
from itertools import islice
d = deque(range(10))
print(d[0], d[-1], d[5]) # 0 9 5
try:
d[2:5]
except TypeError as exc:
print("slicing failed:", type(exc).__name__)
print(list(islice(d, 2, 5))) # [2, 3, 4]itertools.islice is the usual workaround. It still walks the deque from the left, so taking a slice near the end costs O(n), the same as in a linked structure. If you need slices often, you want a list.
The indexing loop trap
This loop looks harmless and is a common performance bug:
from collections import deque
d = deque(range(100_000))
total = 0
for i in range(len(d)):
total += d[i] # each lookup walks blocks from the nearer end
print(total)Each d[i] costs time proportional to how far i is from the nearer end. The loop as a whole is roughly O(n²). On a list the same loop would be O(n). To visit every item, iterate the deque directly with for x in d, which walks the blocks once and is O(n).
Binary search has the same problem. bisect works on any sequence that supports indexing, so it runs on a deque. Each probe is an O(n) index, though, so you lose the benefit of binary search. Use a list for sorted data you search by position.
Operations in the middle
Both types are slow in the middle. deque offers insert(i, x), remove(x), del d[i], and index(x), so code written for lists often runs on a deque unchanged. It does not run faster.
from collections import deque
d = deque("abcde")
d.insert(2, "X")
print(d) # deque(['a', 'b', 'X', 'c', 'd', 'e'])
d.remove("d")
del d[0]
print(d) # deque(['b', 'X', 'c', 'e'])A bounded deque adds one more edge case. insert on a deque that is already at its maxlen raises IndexError, because there is no rule for which end should lose an item. append and appendleft on a full bounded deque are fine. They discard from the opposite end, as described in the earlier chapter on maxlen.
If your algorithm needs many middle insertions, a deque does not help. Reconsider the design, or look at a different structure such as a heap (heapq) for priority order or a sorted container from a third-party package.
Differences that are not about speed
Some behaviors differ even when speed does not matter.
- Equality across types. A deque never equals a list, even with the same items.
deque([1, 2]) == [1, 2]isFalse. Comparelist(d) == otherwhen you need that. - No
sort(), no slice assignment. Usesorted(d)to get a new list, or convert the deque withlist(d). - Mutation during iteration. Changing a deque while looping over it raises
RuntimeError. A list does not raise. It silently skips or repeats items, which is a worse failure. The example below shows the deque behavior. - Extending to the left.
extendleft(iterable)appends each item to the left one at a time, so the items end up in reversed order.
from collections import deque
d = deque([1, 2, 3])
try:
for x in d:
if x == 2:
d.append(99)
except RuntimeError as exc:
print(exc) # deque mutated during iteration
d = deque([3])
d.extendleft([2, 1, 0])
print(d) # deque([0, 1, 2, 3])The second half shows the reversal. The input [2, 1, 0] was added one item at a time on the left, so 0 ended up first.
Memory and iteration speed
Because a list stores references next to each other, scanning one is friendly to the CPU cache. In practice a full pass over a list is somewhat faster than a full pass over a deque of the same length. Both are O(n), and the difference is a constant factor.
A deque has a small fixed overhead per 64 items, for the block links. For a very large deque this overhead is minor. For many tiny deques it adds up, because each deque object and its first block cost more than an empty list. If your program creates millions of small containers, measure memory before choosing a deque.
Thread safety
The Python documentation states that append, appendleft, pop, popleft, and extend on a deque are thread-safe, with the same memory-efficiency guarantee on both ends. That makes a deque a common building block for simple producer and consumer code, where one thread appends and another calls popleft.
Two limits apply. A sequence like "check if d: then d.popleft()" is not atomic as a pair. Another thread can empty the deque between the two steps, so catch IndexError from popleft instead of checking first. For blocking waits and shutdown signalling, use queue.Queue, which is built on a deque and adds locking and conditions.
Worked example: a queue in breadth-first search
Breadth-first search (BFS) visits nodes in order of distance from the start. It takes from the front of a queue and adds to the back, which is the exact access pattern where a deque beats a list.
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
return order
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D", "E"],
"D": ["F"],
"E": ["F"],
"F": [],
}
print(bfs_order(graph, "A")) # ['A', 'B', 'C', 'D', 'E', 'F']With queue.pop(0) on a list, this function would give the same answer. On a graph with millions of nodes, the queue can hold a large frontier at once, and every pop(0) would shift it.
Worked example: a sliding window
A bounded deque keeps the last window values, and a running total avoids re-summing the window each step.
from collections import deque
def moving_average(values, window):
recent = deque(maxlen=window)
total = 0
for value in values:
if len(recent) == window:
total -= recent[0] # this value is about to be discarded
recent.append(value)
total += value
yield total / len(recent)
print(list(moving_average([1, 2, 3, 4, 5], 3)))
# [1.0, 1.5, 2.0, 3.0, 4.0]The code reads recent[0], which is an end index and O(1). It does not read from the middle, so the deque's weak spot never comes up. The maxlen argument handles the eviction.
Using a list as a stack
A stack adds and removes at the same end, and that is the end where a list is fast. append and pop() on a list are O(1), and a list is slightly lighter than a deque. Using a list as a stack is correct and idiomatic. Reach for a deque as a stack only when you also need a bounded size or thread-safe pops.
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # aChoosing between them
The decision follows from which operations dominate.
Use these rules in order:
- If you only touch the right end (a stack, or an append-only log), use a list.
- If you take from one end and add at the other (a queue), use a deque once the queue can exceed a few hundred items.
- If you keep only the most recent items, use a deque with
maxlen. - If you index, slice, sort, or binary-search, use a list.
- If two or more of these conflict, convert at the boundary. Fill a deque, then call
list(d)once when you need a sorted or sliced view.
Summary of trade-offs
- A deque is fast at both ends and slow in the middle. A list is fast on random access and at the right end, and slow at the left end.
- Both have O(n) search, middle insertion, and middle removal.
- A deque has no slicing or
sort(). It raisesRuntimeErrorif you change it during iteration. It never compares equal to a list. - A deque's end operations are documented as thread-safe, but compound check-then-act sequences are not.
- Measure with realistic sizes. The gap between the two types grows with the number of items held.
Exercise
A function processes a task queue with this loop: while tasks: job = tasks.pop(0); run(job), where tasks is a list that often holds 200,000 items. What change fixes the slowdown, and why is the original slow? Would changing it also speed up tasks[len(tasks) // 2]?
Show answer
Build tasks as deque(tasks) and use tasks.popleft(). The list version is slow because pop(0) shifts every remaining reference one slot left, so each pop costs O(n) and the full drain costs O(n²). popleft is O(1), so the full drain is O(n). The change does not help tasks[len(tasks) // 2]. Indexing the middle of a deque is O(n) because it walks blocks from an end, while on a list it is O(1). If the code needs middle access often, a deque is the wrong choice.
Exercise
Predict what this code prints, then explain each result: from collections import deque, d = deque([1, 2, 3]), print(d == [1, 2, 3]), print(list(d) == [1, 2, 3]), d.extendleft([9, 8]), print(d).
Show answer
It prints False, then True, then deque([8, 9, 1, 2, 3]). A deque never compares equal to a list, even with the same items, so the first comparison is False. Converting with list(d) first gives equal lists, so the second is True. extendleft adds the items one at a time on the left, so 9 goes in first and 8 goes in front of it, which reverses the order of the input.