Sub topic 6
Queues and stacks with deque
This chapter assumes you know basic Python loops and functions, how list and dict work, and how to import names from the standard library. Here you learn the deque operations that let one container act as a queue or a stack.
What a deque is
A deque (pronounced "deck", short for double-ended queue) is a sequence that lets you add and remove items at both ends. You import it from the collections module:
from collections import dequeA list is fast at its right end. Adding or removing at the left end forces Python to shift every other item. A deque is built so that both ends are fast. Because of that, it suits two common patterns:
- A queue is first in, first out (FIFO). The item that has waited longest leaves first.
- A stack is last in, first out (LIFO). The item added most recently leaves first.
The four core methods
| Method | End | Effect |
|---|---|---|
| `append(x)` | right | Adds `x` |
| `appendleft(x)` | left | Adds `x` |
| `pop()` | right | Removes and returns the last item |
| `popleft()` | left | Removes and returns the first item |
Here is each method in use:
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
d.rotate(1)
print(d) # deque([3, 1, 2])rotate(1) moves the last item to the front. The next chapter covers rotate in more detail. Note that list has pop() but no popleft(). The left-end methods are what make deque useful.
Using a deque as a queue
For a queue, add at one end and remove at the other. The usual choice is append to join and popleft to leave:
from collections import deque
line = deque()
line.append("Ana")
line.append("Ben")
line.append("Chi")
while line:
print("serving", line.popleft())
# serving Ana
# serving Ben
# serving ChiAn empty deque is falsy, so while line: is the idiomatic way to process items until none remain. Items leave in the order they arrived.
A common use is breadth-first search, which visits nodes level by level. It needs a queue, because nodes found first must be explored first:
from collections import deque
graph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": [],
}
def bfs(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
print(bfs("A")) # ['A', 'B', 'C', 'D']Using a deque as a stack
For a stack, add and remove at the same end. Use append and pop:
from collections import deque
history = deque()
history.append("open file")
history.append("type text")
history.append("delete line")
print(history.pop()) # delete line
print(history.pop()) # type text
print(history[-1]) # open fileReading history[-1] shows the top of the stack without removing it. A plain list works just as well for a stack, since append and pop are fast on a list. Choose deque when you also need the left end, or when you want a container that signals "queue" to the reader.
Building and extending
You can create a deque from any iterable. You can also add many items at once:
from collections import deque
d = deque("abc")
d.extend("de")
print(d) # deque(['a', 'b', 'c', 'd', 'e'])
e = deque()
e.extendleft([1, 2, 3])
print(e) # deque([3, 2, 1])extendleft calls appendleft once per item, so the input order ends up reversed. This surprises many people. If you want the order preserved, reverse the input first: e.extendleft(reversed([1, 2, 3])).
Common errors
Popping from an empty deque. Both pop() and popleft() raise IndexError when there is nothing to remove:
from collections import deque
try:
deque().popleft()
except IndexError as error:
print(error) # pop from an empty dequeGuard the call with if d: or a while d: loop, or catch the exception.
Slicing. A deque supports indexing such as d[0] and d[-1], but not slices. d[1:3] raises TypeError. To slice, convert first: list(d)[1:3], or use itertools.islice(d, 1, 3).
Indexing in the middle. d[0] and d[-1] are fast. An index near the middle takes time proportional to the deque's length. If you are looping with d[i] across a large deque, a list is the better fit.
Using list.pop(0) for a queue. This works but gets slower as the list grows, because every remaining item shifts left. Switching to deque.popleft() removes that cost.
Summary of the pattern
- Queue:
appendto add,popleftto remove. - Stack:
appendto add,popto remove. - Use
while d:to drain either one. extendleftreverses the order of its input.- Empty removals raise
IndexError, and slicing is not supported.
Exercise
You have tasks = deque(["a", "b", "c"]). You call tasks.appendleft("z"), then tasks.pop(), then tasks.popleft(). What does tasks contain at the end, and what did each of the two removal calls return?
Show answer
After appendleft("z") the deque is deque(['z', 'a', 'b', 'c']). pop() removes and returns 'c' from the right, leaving ['z', 'a', 'b']. popleft() removes and returns 'z' from the left. The final deque is deque(['a', 'b']).
Exercise
Write a function last_in_first_out(items) that takes a list, pushes every item onto a deque used as a stack, and returns a new list of the items in the order they pop off.
Show answer
from collections import deque def lastinfirstout(items): stack = deque() for item in items: stack.append(item) result = [] while stack: result.append(stack.pop()) return result print(lastinfirstout([1, 2, 3])) # [3, 2, 1]