Sub topic 6
Deques: A Queue Open at Both Ends
A deque (pronounced "deck", short for double-ended queue) is a sequence where you can add and remove items at both the front and the back. This chapter covers the deque as an abstract data type and how Python's collections.deque exposes it.
This chapter assumes you know basic Python syntax, lists and indexing, and Big-O notation. It also assumes you have seen the queue operations enqueue and dequeue and the idea of FIFO (first in, first out) ordering.
The deque abstract data type
A queue restricts you to one entry point, the back, and one exit point, the front. A deque removes that restriction. It supports four core operations, each at O(1) cost in a good implementation:
| Operation | Effect | Python name |
|---|---|---|
| Add at back | Insert after the last item | `append(x)` |
| Add at front | Insert before the first item | `appendleft(x)` |
| Remove from back | Return and delete the last item | `pop()` |
| Remove from front | Return and delete the first item | `popleft()` |
Most implementations also offer peeking at either end and checking the size.
A deque is more general than both a queue and a stack:
- Use only
appendandpopleft, and it behaves as a FIFO queue. - Use only
appendandpop, and it behaves as a LIFO stack. - Use all four, and you get behavior neither structure can give you alone.
Why a list is the wrong tool
A Python list is an array. Operations at the back are cheap, but operations at the front are not. Both list.pop(0) and list.insert(0, x) shift every other element, so they cost O(n). A deque exists to make the front as cheap as the back.
How collections.deque works
CPython implements collections.deque as a doubly linked list of fixed-size blocks, where each block holds an array of items. This design gives O(1) operations at both ends without shifting elements. It also uses far less memory per item than one linked node per element would.
The trade-off is in the middle. Indexing such as d[i] walks across blocks, so it costs O(n) in the worst case. Indexing near either end is fast, but the middle is the slowest part.
Using collections.deque
Here is each core operation, plus rotate:
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)After the pops, the deque holds [1, 2, 3]. The call rotate(1) moves each element one step to the right. The last element, 3, wraps around to the front. A negative argument rotates left.
Other useful methods include extend, extendleft, clear, count, and remove. Note that extendleft adds items one at a time, so the input order ends up reversed:
from collections import deque
d = deque([3])
d.extendleft([2, 1, 0])
print(d) # deque([0, 1, 2, 3])Here the iterable [2, 1, 0] is inserted one item at a time at the front, so 2 goes first and 0 ends up at the very front.
Common errors
Popping from an empty deque. Both pop() and popleft() raise IndexError on an empty deque. Check the deque's truthiness first:
from collections import deque
d = deque()
if d:
d.popleft()
else:
print("nothing to remove")Slicing. A deque does not support slices. d[1:3] raises TypeError. Convert to a list first, or use itertools.islice.
Indexing in a loop. Writing for i in range(len(d)): d[i] makes each access potentially O(n), which can turn the loop quadratic. Iterate directly with for x in d instead.
Sharing across threads. Single append and popleft calls on a deque are atomic in CPython. But a deque has no blocking behavior and no way to wait for work to finish. For producer-consumer coordination, a later chapter covers queue.Queue.
Choosing between list and deque
| Need | Better choice |
|---|---|
| Add and remove at the back only | `list` |
| Add and remove at the front | `deque` |
| Fast `d[i]` anywhere | `list` |
| Slicing | `list` |
| Queue with FIFO order | `deque` |
Exercise
You write items = deque([1, 2, 3, 4]) and then call items.rotate(-1). What does items contain afterward, and which end does the element that moved end up on?
Show answer
It contains deque([2, 3, 4, 1]). A negative argument rotates left, so the first element, 1, moves around to the back.
Exercise
A teammate uses for i in range(len(d)): total += d[i] on a deque with a million items. Why can this be slow, and what is the fix?
Show answer
Indexing into the middle of a deque costs O(n), so the loop can become quadratic. Iterate directly with for x in d: total += x, which visits each item once in O(n) total.