Sub topic 7
Using collections.deque in practice
This chapter assumes you know basic Python syntax, list indexing, and Big-O notation. You should also know what a queue is and why list.pop(0) is slow. Here you will use collections.deque, the standard double-ended queue in Python, and learn where it can trip you up.
What deque gives you
A deque (pronounced "deck") supports appends and pops at both ends in O(1) time. CPython implements it as a doubly linked list of fixed-size blocks. Each block holds many items, so it uses memory more efficiently than one node per item. It also avoids the shifting that makes list.pop(0) cost O(n).
| Operation | `list` | `deque` |
|---|---|---|
| Append at right | O(1) amortized | O(1) |
| Pop from right | O(1) | O(1) |
| Insert or pop at left | O(n) | O(1) |
| Index in the middle, `d[i]` | O(1) | O(n) |
The last row is the price you pay. A deque is built for work at its ends, not for random access.
Core operations
from collections import deque
d = deque([1, 2, 3])
d.append(4) # deque([1, 2, 3, 4])
d.appendleft(0) # deque([0, 1, 2, 3, 4])
print(d.popleft()) # 0
print(d.pop()) # 4
d.rotate(1) # deque([3, 1, 2])
print(d)Walk through the state after each line:
append(4)adds to the right end.appendleft(0)adds to the left end.popleft()removes and returns0, andpop()removes and returns4. The deque is back to[1, 2, 3].rotate(1)moves the last item to the front, giving[3, 1, 2]. A negative argument rotates the other way.
For a plain FIFO queue, use append to enqueue and popleft to dequeue. Peek at the front with d[0] and at the back with d[-1]. Both are O(1). Check the size with len(d).
Other useful methods
extend(iterable)appends each item on the right.extendleft(iterable)appends each item on the left, one at a time. The result is in reversed order:deque([1, 2]).extendleft([3, 4])givesdeque([4, 3, 1, 2]).clear()empties the deque.remove(value)deletes the first match and costs O(n).copy()makes a shallow copy.
from collections import deque
d = deque([1, 2])
d.extendleft([3, 4])
print(d) # deque([4, 3, 1, 2])Common errors
Popping from an empty deque. Both pop() and popleft() raise IndexError when the deque is empty. Guard the call with if d: or catch the exception.
from collections import deque
d = deque()
try:
d.popleft()
except IndexError:
print("nothing to remove")Slicing. A deque does not support slices such as d[1:3]. It raises TypeError. Convert to a list first, or use itertools.islice(d, 1, 3).
Indexing in a loop. Writing for i in range(len(d)): d[i] is O(n²) overall, because each middle access is O(n). Iterate directly with for x in d: instead.
Mutating while iterating. Changing a deque during iteration raises RuntimeError: deque mutated during iteration. Iterate over a copy, or collect changes and apply them afterward.
Wrong choice for random access. If you read from the middle often, use a list. If you only work at the ends, use a deque.
Choosing between list and deque
Use a deque when you add or remove at the left end, such as a FIFO queue, a work list in a search, or a history of recent events. Use a list when you need fast indexing, slicing, or sorting in place. Converting with list(d) costs O(n), so avoid doing it inside a hot loop.
Exercise
You enqueue tasks with append and process them with popleft. A teammate says to replace the deque with a list and use pop(0) because "the code is simpler." Name the cost that changes, and give the result of deque([1, 2]).extendleft([3, 4]).
Show answer
Dequeuing from the front of a list with pop(0) becomes O(n), because every remaining item shifts left. popleft() on a deque is O(1). The result of extendleft([3, 4]) is deque([4, 3, 1, 2]), since extendleft adds items one at a time on the left, which reverses their order.
Exercise
This code raises an error. Why, and how do you fix it? d = deque([1, 2, 3, 4]); print(d[1:3])
Show answer
Deques do not support slicing, so it raises TypeError. Use list(d)[1:3], or list(itertools.islice(d, 1, 3)), which gives [2, 3].