Sub topic 15
Lists as stacks, and when to use deque instead
This chapter assumes you know how to create lists, use append and pop, and loop over a list. You should also know that list operations have different costs, which the previous chapter on performance covered. Here you will use those costs to decide when a list is the right tool for a stack or a queue, and when collections.deque is better.
Stacks and queues in one minute
A stack is a collection where the last item added is the first one removed. This is called last in, first out (LIFO). A queue removes items in the order they arrived, which is first in, first out (FIFO).
Both structures need only two operations: add at one end, and remove from one end. Where those ends are decides which structure you have, and it also decides which Python container fits.
A list works well as a stack
A list stores its items in one contiguous block of memory. Adding or removing at the end only touches the last slot, so append and pop() take amortized constant time, written O(1). "Amortized" means that an occasional append has to resize the block and copy every item. The cost of those copies, averaged over many appends, is still constant per operation.
stack = []
stack.append("a") # push
stack.append("b")
stack.append("c")
print(stack[-1]) # c (peek: look without removing)
print(stack.pop()) # c (pop: remove and return)
print(stack) # ['a', 'b']
print(not stack) # False (an empty list is falsy)Three idioms cover most stack code:
- Push with
append(x). - Peek with
stack[-1]. This raisesIndexErrorif the stack is empty. - Test for emptiness with
if stack:orif not stack:, not withlen(stack) == 0.
A classic use is checking that brackets are balanced. Each opening bracket is pushed. Each closing bracket must match the most recently opened one, which is exactly the top of the stack.
def is_balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
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("((")) # FalseThe check not stack or ... comes first on purpose. Without it, a closing bracket with nothing open would call pop() on an empty list and raise IndexError. The final return not stack catches the case where openers are left over.
A list is a poor queue
To use a list as a queue, you add at the end and remove from the front:
queue = [1, 2, 3]
queue.append(4)
print(queue.pop(0)) # 1
print(queue) # [2, 3, 4]This is correct, but slow for large queues. Removing index 0 leaves a gap at the start of the memory block, so every remaining item shifts one slot left. That costs O(n), where n is the number of items. insert(0, x) has the same problem in reverse. For ten items nobody notices. For hundreds of thousands of items processed in a loop, the total work grows with the square of the size.
You can measure this yourself. The script below drains the same number of items from a list and from a deque. Exact times depend on your machine, but the list version is dramatically slower.
import timeit
from collections import deque
N = 100_000
def drain_list():
items = list(range(N))
while items:
items.pop(0)
def drain_deque():
items = deque(range(N))
while items:
items.popleft()
print("list :", timeit.timeit(drain_list, number=1))
print("deque:", timeit.timeit(drain_deque, number=1))deque: constant-time operations at both ends
collections.deque (pronounced "deck", short for double-ended queue) is built for adding and removing at either end. Internally it is a linked sequence of fixed-size blocks, so the ends can grow and shrink without shifting anything.
from collections import deque
d = deque([2, 3])
d.append(4) # right end
d.appendleft(1) # left end
print(d) # deque([1, 2, 3, 4])
print(d.pop()) # 4
print(d.popleft()) # 1
print(list(d)) # [2, 3]All four operations (append, appendleft, pop, popleft) are O(1). The method names mirror list methods, so moving from a list to a deque is usually a small edit.
Here is a breadth-first traversal of a graph. It visits nodes in order of distance from the start, which needs a true FIFO queue.
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(bfs_order(graph, "A")) # ['A', 'B', 'C', 'D']Extra deque features
A deque accepts a maxlen argument. When the deque is full, adding an item at one end silently discards an item from the other end. This is a compact way to keep "the last N things".
from collections import deque
recent = deque(maxlen=3)
for n in range(5):
recent.append(n)
print(recent) # deque([2, 3, 4], maxlen=3)rotate(k) shifts items k steps to the right, wrapping around. A negative k rotates left.
from collections import deque
d = deque([1, 2, 3, 4])
d.rotate(1)
print(d) # deque([4, 1, 2, 3])A deque also supports extendleft, clear, count, remove, reverse, and in. One detail surprises people: extendleft([1, 2, 3]) adds the items one at a time to the left, so they end up in reverse order.
Where deque is weaker than a list
A deque is not a drop-in replacement for a list. The trade-offs matter:
- Indexing in the middle is O(n).
d[0]andd[-1]are fast, butd[len(d) // 2]walks across blocks. A list gives O(1) access at any index. - No slicing.
d[1:3]raisesTypeError. Convert withlist(d)first, or useitertools.islice. - No
sortmethod. Usesorted(d), which returns a list. - Memory. Each block carries bookkeeping overhead, so a deque of the same items usually uses somewhat more memory than a list.
| Need | list | deque |
|---|---|---|
| Push and pop at the right end | O(1) amortized | O(1) |
| Push and pop at the left end | O(n) | O(1) |
| Read `x[i]` anywhere | O(1) | O(1) at the ends, O(n) in the middle |
| Slicing | Yes | No |
| Sort in place | `sort()` | Not available |
| Bounded "last N" buffer | Manual | `maxlen` |
Choosing between them
For small collections (a few dozen items) the difference is not measurable, so choose whichever reads best. Switch to a deque when a queue can grow large, or when you process it in a tight loop.
Common errors
- Popping from an empty container. Both
[].pop()anddeque().pop()raiseIndexError.deque().popleft()does too. Checkif stack:first, or catch the exception if empty is rare. - Using
pop(0)in a hot loop. The code works and passes small tests, then slows down badly on real data. Replace it with a deque andpopleft(). - Treating
maxlenas an error check. A full bounded deque never raises. It drops items without warning, so do not use it when losing data would be a bug. - Slicing a deque.
d[:3]fails. Uselist(itertools.islice(d, 3)). - Mutating while iterating. Changing a deque during a
forloop over it raisesRuntimeError. Use awhile d:loop withpopleft(), asbfs_orderdoes.
When neither is the right tool
A deque's individual appends and pops are safe to call from several threads. Coordinating producers and consumers still needs more than that, such as blocking until an item arrives. For that, the standard library's queue.Queue adds locking and waiting. If you need the smallest item first, rather than the oldest, use a priority queue with the heapq module.
Exercise
A program reads 500,000 job IDs into a list and then repeatedly handles the oldest one with jobs.pop(0) until the list is empty. Why does this get slow, and what is the fix?
Show answer
Each pop(0) shifts every remaining item one position left, so each call costs O(n) and the whole loop costs roughly O(n squared). Store the jobs in collections.deque and call popleft(), which is O(1) per call.
Exercise
Write code that keeps only the 3 most recent readings from the stream 10, 20, 30, 40, 50 and prints the result as a plain list.
Show answer
from collections import deque readings = deque(maxlen=3) for r in [10, 20, 30, 40, 50]: readings.append(r) print(list(readings)) # [30, 40, 50]
Exercise
You have d = deque([1, 2, 3, 4, 5]). Why does d[1:3] fail, and how can you get [2, 3] from it?
Show answer
A deque does not support slice objects as indexes, so d[1:3] raises TypeError. Convert first with list(d)[1:3], or use list(itertools.islice(d, 1, 3)), which gives [2, 3].