Stacks and Queues in Python: LIFO, FIFO and deque
Stacks and queues are containers defined by the order in which items come back out. They have tiny interfaces, which is exactly why they show up everywhere: function calls, undo history, parsing, scheduling and graph search all rely on one or the other. Examples use Python 3.10 or later and only the standard library.
LIFO and FIFO
A stack is last in, first out (LIFO). Think of a pile of plates: you add to the top and take from the top, so the plate you put down most recently is the first one you pick up. Its operations are push (add to the top), pop (remove the top) and peek (look at the top without removing it).
A queue is first in, first out (FIFO). Think of a line at a counter: people join at the back and are served from the front, so the one who has waited longest goes next. Its operations are enqueue (add at the back) and dequeue (remove from the front).
Both are abstract interfaces: they say what the operations do, not how they are stored. A good implementation makes every one of these operations O(1).
A Python list as a stack
A Python list already is a good stack, as long as the top is the end of the list. append pushes, pop() with no argument pops, and stack[-1] peeks.
stack = []
stack.append("a") # push
stack.append("b")
stack.append("c")
print(stack[-1]) # peek at the top: "c"
print(stack.pop()) # pop removes the most recent push
print(stack.pop())
print(stack, len(stack) == 0)
c
c
b
['a'] False
pop() from the end is O(1). append is amortized O(1): a list is a dynamic array, so an append occasionally has to copy everything into a larger block, but because the capacity grows in proportion to the size, those copies average out to a constant per push over any sequence of pushes. The Amortized Analysis Calculator shows the arithmetic for a doubling array (1,000 appends cost 2,023 unit steps in total, 2.02 each). Calling pop() on an empty list raises IndexError, so check if stack: first when the stack may be empty.
Balanced brackets with a stack
The standard stack exercise checks whether every bracket in a string is closed by the matching kind in the right order. Push each opener. On each closer, the top of the stack must be the matching opener; pop it. At the end, the stack must be empty.
PAIRS = {")": "(", "]": "[", "}": "{"}
def balanced(text):
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 # closer with no matching opener
return not stack # leftover openers are unbalanced
for s in ["(a[b]{c})", "([)]", "((", "", "}{"]:
print(repr(s), balanced(s))
'(a[b]{c})' True
'([)]' False
'((' False
'' True
'}{' False
"([)]" fails because the ) arrives while [ is on top. The stack is the right structure because the bracket that must close next is always the one opened most recently. The check runs in O(n) time and uses O(n) space in the worst case (a string of n openers). Compilers use the same idea for nested blocks, and your own program uses a stack for function calls: each call pushes a frame, each return pops it, which is why deep recursion can exhaust it (see recursion explained).
Why a list is a poor queue
You could enqueue with append and dequeue with pop(0), and for a handful of items it works. But pop(0) removes the first slot of a dynamic array, so every remaining item shifts one place to the left: O(n) per dequeue. Processing n items through such a queue costs O(n^2) in total. insert(0, x) has the same problem in the other direction.
collections.deque (a double-ended queue) is built for this. It supports append, appendleft, pop and popleft, each O(1), so it makes a proper queue:
from collections import deque
tasks = deque()
for name in ["resize image", "send email", "write log"]:
tasks.append(name) # enqueue at the back
while tasks:
task = tasks.popleft() # dequeue from the front, O(1)
print("processing", task)
if task == "send email":
tasks.append("retry email") # new work joins the back of the line
processing resize image
processing send email
processing write log
processing retry email
Tasks come out in arrival order, and the retry joins the back of the line, behind everything already waiting. The same loop, with "visit the neighbors of this node" in place of "process the task", is breadth-first search: the queue makes sure nodes are explored in order of their distance from the start. The BFS and DFS post builds it, and also shows that swapping the queue for a stack turns the search into depth-first order.
A deque as both
Because a deque is O(1) at both ends, it can act as a stack, a queue, or something in between. With maxlen set it becomes a fixed-size window that discards its oldest item automatically, which is handy for "the last k events":
from collections import deque
recent = deque(maxlen=3) # keeps only the last 3 items
for page in ["home", "docs", "blog", "about", "docs"]:
recent.append(page) # the oldest falls off the left end
print(list(recent))
d = deque([1, 2, 3])
d.appendleft(0) # use the left end like a stack top
print(d.popleft(), d.pop(), list(d))
['blog', 'about', 'docs']
0 3 [1, 2]
The trade-off is indexing: a deque is fast at its ends, but d[i] slows to O(n) toward the middle, so for random access by position a list is better. For a pure stack a list is the usual choice; for anything that removes from the front, use a deque.
Priority queues are different
A priority queue sounds like a queue but does not serve items in arrival order. It hands back the item with the smallest (or largest) priority, whenever it was added. A deque cannot do that efficiently; the usual structure is a binary heap, which supports push and pop in O(log n). Python provides it in the heapq module, covered in heaps and priority queues.
Summary of costs
| Structure | Add | Remove | Peek |
|---|---|---|---|
| Stack on a list (top at the end) | append, amortized O(1) | pop(), O(1) | s[-1], O(1) |
| Queue on a list (front at index 0) | append, amortized O(1) | pop(0), O(n) | q[0], O(1) |
| Queue on a deque | append, O(1) | popleft, O(1) | q[0], O(1) |
| Priority queue on a heap | heappush, O(log n) | heappop, O(log n) | h[0], O(1) |
Check yourself
- What does
balanced("(()")return, and which line decides it? (False; the finalreturn not stack, because one opener is left.) - A program dequeues a million items with
list.pop(0). Why is it slow, and what is the one-line fix? (Each pop shifts every remaining item; usecollections.dequeandpopleft.) - Undo history in an editor: stack or queue? (A stack: undo reverses the most recent change first.)