Sub topic 6
Queues and stacks with deque
This chapter assumes you can write loops and functions, use list and dict, and import names from the standard library. Earlier chapters covered Counter and defaultdict. This one introduces deque, the container you reach for when items enter and leave at the ends of a sequence.
What a deque is
A deque (pronounced "deck", short for double-ended queue) is a sequence that supports fast adds and removes at both ends. It lives in the collections module.
from collections import deque
empty = deque()
from_list = deque([1, 2, 3])
from_text = deque("abc")
print(empty) # deque([])
print(from_list) # deque([1, 2, 3])
print(from_text) # deque(['a', 'b', 'c'])The constructor takes any iterable, like list. A deque looks like a list in many ways:
len(d)gives the number of items.for item in diterates from left to right.x in dtests membership by scanning.- An empty deque is falsy, and a non-empty one is truthy.
The difference is in which operations are cheap. A list is fast at the right end only. A deque is fast at both ends.
The four core operations
Four methods cover most uses of a deque.
| Method | Effect | Returns |
|---|---|---|
| `append(x)` | Adds `x` at the right end | `None` |
| `appendleft(x)` | Adds `x` at the left end | `None` |
| `pop()` | Removes the rightmost item | The removed item |
| `popleft()` | Removes the leftmost item | The removed item |
Each of these takes constant time, which computer scientists write as O(1). The cost does not grow with the deque's length.
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0)
d.append(4)
print(d) # deque([0, 1, 2, 3, 4])
print(d.popleft()) # 0
print(d.pop()) # 4
print(d) # deque([1, 2, 3])The names follow one rule. Methods without left act on the right end, which is the same end list.append and list.pop use. Methods with left act on the left end. list has no equivalent of popleft. The closest is list.pop(0), which is slow, as discussed below.
Using a deque as a queue
A queue is first in, first out (FIFO). Items leave in the order they arrived, like people in a line. To build one, add at one end and remove from the other. The usual convention is append to enqueue and popleft to dequeue.
from collections import deque
line = deque()
line.append("Ana")
line.append("Ben")
line.append("Chloe")
while line:
person = line.popleft()
print("Serving", person)
# Serving Ana
# Serving Ben
# Serving ChloeThe condition while line: relies on truthiness. It runs until the deque is empty, so no counter or length check is needed.
Worked example: breadth-first search
Breadth-first search (BFS) visits the nodes of a graph in order of distance from a start node. It needs a FIFO queue of nodes still to visit.
from collections import deque
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D", "E"],
"D": ["F"],
"E": ["F"],
"F": [],
}
def bfs_order(graph, start):
seen = {start}
order = []
queue = deque([start])
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
print(bfs_order(graph, "A")) # ['A', 'B', 'C', 'D', 'E', 'F']Trace the first steps to see the queue at work:
- The queue starts as
[A]. PopA, then enqueue its neighborsBandC. - Pop
Band enqueueD. The queue is now[C, D]. - Pop
C. Its neighborDis already inseen, so onlyEis enqueued. - Nodes at distance 1 (
B,C) are handled before nodes at distance 2 (D,E). That is the effect of FIFO order.
The seen set marks a node when it is enqueued, not when it is dequeued. That stops the same node from being queued twice. Swap the queue for a stack and the same loop becomes a depth-first search.
Using a deque as a stack
A stack is last in, first out (LIFO). The most recent item leaves first, like a pile of plates. Add and remove at the same end. With a deque, use append and pop, which is exactly how you would use a list as a stack.
from collections import deque
stack = deque()
stack.append("page1")
stack.append("page2")
stack.append("page3")
print(stack.pop()) # page3
print(stack.pop()) # page2
print(stack[-1]) # page1, peek at the top without removing itIndexing at either end (d[0], d[-1]) takes constant time. That makes it a cheap way to peek at the next item to leave.
Worked example: balanced brackets
A stack suits any problem where the most recent unfinished thing must be resolved first. Checking that brackets are balanced is the standard case.
from collections import deque
def is_balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = deque()
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(is_balanced("(a[b]{c})")) # True
print(is_balanced("(]")) # False
print(is_balanced("((")) # FalseEvery opening bracket is pushed. Every closing bracket must match the most recent unmatched opener, which is the top of the stack. The not stack check before pop() handles input like ")", where a closer arrives with nothing to match. The final return not stack catches leftover openers.
For a stack alone, a plain list works just as well. A deque helps when the same structure serves both ends, for example in a work-stealing scheduler or a double-ended search. It also states your intent: a reader sees deque and knows items move in and out at the ends.
Adding and removing several items
Two methods add many items at once.
from collections import deque
d = deque([3])
d.extend([4, 5])
d.extendleft([2, 1, 0])
print(d) # deque([0, 1, 2, 3, 4, 5])
e = deque()
e.extendleft("abc")
print(e) # deque(['c', 'b', 'a'])extend adds items to the right in iteration order. extendleft adds them to the left one at a time. Each item lands in front of the previous one, so the input appears reversed in the result. The second example makes this visible: "abc" becomes c, b, a. This surprises people who expect extendleft to mirror extend.
clear() removes everything. copy() makes a shallow copy. reverse() reverses the deque in place and returns None, as list.reverse does.
Working with the middle
A deque supports most list-style access, but the middle is a weaker spot.
from collections import deque
d = deque("abcde")
print(d[0], d[-1], d[2]) # a e c
d[2] = "X"
print(d) # deque(['a', 'b', 'X', 'd', 'e'])
d.insert(1, "Y")
print(d) # deque(['a', 'Y', 'b', 'X', 'd', 'e'])
d.remove("X")
print(d.index("d")) # 3
print(d.count("a")) # 1All of these work. insert, remove, index, count and indexing near the middle scan the data, so they cost time proportional to the distance involved. A deque is built for the ends. If your code indexes into the middle in a loop, a list is probably the better choice. The chapter on deque performance covers the numbers.
Two things a deque does not do:
from collections import deque
d = deque([10, 20, 30, 40])
try:
d[1:3]
except TypeError as e:
print(e) # sequence index must be integer, not 'slice'Slicing is not supported. If you need a slice, convert first with list(d)[1:3], or use itertools.islice(d, 1, 3) to avoid building the full list.
The second limit is that you must not change a deque while you iterate over it.
from collections import deque
d = deque([1, 2, 3])
try:
for x in d:
d.append(x)
except RuntimeError as e:
print(e) # deque mutated during iterationLoop over list(d) if you need to modify d inside the loop. The while d: d.popleft() pattern is safe because it does not iterate.
Empty deques and errors
Popping from an empty deque raises IndexError. Both pop and popleft do this.
from collections import deque
d = deque()
try:
d.popleft()
except IndexError as e:
print(e) # pop from an empty dequeThere are two common ways to handle it. Test first:
from collections import deque
tasks = deque(["a", "b"])
if tasks:
item = tasks.popleft()Or catch the exception, which reads well when empty is rare:
from collections import deque
tasks = deque()
try:
item = tasks.popleft()
except IndexError:
item = Nonedeque has no pop(default) form. Unlike dict.pop, you cannot supply a fallback value, so wrap the call yourself if you want one.
Why not just use a list
A list can imitate a queue with pop(0) and insert(0, x). The results are correct, but the cost is not. A list stores its items in one contiguous block. Removing the first item shifts every other item one slot to the left, which takes time proportional to the length. A deque stores its items in linked blocks, so adding or removing at an end touches only a small block.
from collections import deque
from time import perf_counter
N = 50_000
lst = list(range(N))
start = perf_counter()
while lst:
lst.pop(0)
list_time = perf_counter() - start
dq = deque(range(N))
start = perf_counter()
while dq:
dq.popleft()
deque_time = perf_counter() - start
print(f"list.pop(0): {list_time:.4f}s")
print(f"deque.popleft(): {deque_time:.4f}s")The exact times depend on your machine, but the deque version is typically many times faster, and the gap widens as N grows. With small lists you will not notice. In a queue that holds hundreds of thousands of items, pop(0) becomes the bottleneck.
Threads and the queue module
append, appendleft, pop and popleft are atomic in CPython. That means two threads calling them on the same deque will not corrupt its internal state. This makes a deque a workable shared buffer for simple producer and consumer code.
For single-threaded code, such as BFS, parsing and simulations, a plain deque is the right tool.
Common mistakes
- Using
pop()where you meantpopleft(). The first removes from the right, so the structure behaves as a stack instead of a queue. The program runs without error and produces the wrong order. - Expecting
extendleftto preserve order. It reverses the input. - Slicing a deque. Convert to a list or use
itertools.islice. - Modifying a deque while looping over it. Loop over a copy or use
while d:. - Assuming
d.pop()accepts an index. It takes no argument. Usedel d[i]ord.remove(value)for the middle. - Indexing into the middle repeatedly. Each access walks through blocks, so choose a list if you need random access.
Exercise
A print queue should serve jobs in the order they arrive. A colleague writes jobs = deque(), uses jobs.append(job) to add, and jobs.pop() to take the next job. Jobs print in the wrong order. What is the bug, and what is the fix? Also, what happens when jobs.popleft() runs on an empty deque, and how would you guard against it?
Show answer
pop() removes from the right end, the same end append adds to, so the deque acts as a stack (last in, first out). The fix is to take jobs with jobs.popleft(), which gives first in, first out order. Calling popleft() on an empty deque raises IndexError: pop from an empty deque. Guard with if jobs: before the call, or wrap the call in try and except IndexError.
Exercise
Predict the output of this code, then explain the result. from collections import deque d = deque([3]) d.extendleft([2, 1, 0]) d.extend([4, 5]) print(d.popleft(), d.pop(), list(d))
Show answer
It prints 0 5 [1, 2, 3, 4]. extendleft([2, 1, 0]) adds 2, then 1, then 0 to the left, so the deque becomes [0, 1, 2, 3]. extend([4, 5]) gives [0, 1, 2, 3, 4, 5]. popleft() returns 0, pop() returns 5, and the remaining items are [1, 2, 3, 4].
Exercise
Write a function reverse_words(sentence) that uses a deque as a stack to return the words of a sentence in reverse order, joined by single spaces. For example, reverse_words("one two three") returns "three two one".
Show answer
from collections import deque
def reversewords(sentence):
stack = deque()
for word in sentence.split():
stack.append(word)
result = []
while stack:
result.append(stack.pop())
return " ".join(result)
print(reversewords("one two three")) # three two one
Each word is pushed on the right, then popped from the right, so the last word comes out first. deque(sentence.split()) followed by popleft on a reversed sequence would also work, but the stack form shows LIFO order directly.