Stacks & Queues
Two structures behind a lot of software
A complete, practical guide to LIFO and FIFO structures in Python β how to implement them with lists, collections.deque, and the queue module, and when each one is the right tool.
from collections import deque stack = [] stack.append("a"); stack.append("b"); stack.append("c") print(stack.pop()) # c β last in, first out queue = deque() queue.append("a"); queue.append("b"); queue.append("c") print(queue.popleft()) # a β first in, first out
c
a
π§± Two Access Rules, Many Uses
The difference is which end you remove from
LIFO vs FIFO
A stack follows Last In, First Out: the most recently added
item is the first one removed. Think of a stack of plates β you take the top one off, not the
bottom. Python's list is a natural stack, because append() and pop()
both operate on the end, and both are O(1).
A queue follows First In, First Out: the oldest item is removed first.
Think of a line at a checkout β the person who arrived first is served first. A plain list is a
poor queue, because pop(0) shifts every remaining element and is O(n).
collections.deque provides O(1) operations at both ends, which makes it the
correct choice.
Both structures show up constantly in real code. Stacks power function calls, undo systems, expression parsing, and depth-first search. Queues power task scheduling, message passing, breadth-first search, and buffered I/O. Knowing which one a problem calls for is often the whole design decision.
The right tool depends on the end you remove from
Remove from the end β list is fine. Remove from the front β use deque. Need thread-safe blocking β use the queue module. The three sections below cover each case.
- βImplement a stack with a list and understand why it's O(1)
- βImplement a queue correctly, without the O(n) trap
- βUse
collections.dequefor efficient double-ended access - βUse the
queuemodule for thread-safe producer/consumer patterns - βChoose the right structure for each problem
- βBuild real examples: balanced brackets, undo, and BFS
π₯ Stacks β Last In, First Out
A list used from one end
A Python list is already a stack. append(x) pushes, pop() removes the most recent item, and items[-1] peeks at it. All three are O(1), which is exactly what a stack needs.
stack = [] stack.append("a") # push stack.append("b") stack.append("c") print(stack) # ['a', 'b', 'c'] print(stack[-1]) # 'c' β peek print(stack.pop()) # 'c' β pop print(stack.pop()) # 'b' print(stack) # ['a'] print(len(stack)) # 1 print(not stack) # False
Guard against popping an empty stack
stack = ["only"] stack.pop() try: stack.pop() except IndexError: print("stack is empty") # Or check first: if stack: stack.pop() else: print("nothing to pop")
pop() on an empty list raises IndexError. Checking if stack: is the idiomatic guard β it's also the fastest, since list.__bool__ is O(1).
A small Stack class
class Stack: def __init__(self): self._items = [] def push(self, item): self._items.append(item) def pop(self): if not self._items: raise IndexError("pop from empty stack") return self._items.pop() def peek(self): if not self._items: raise IndexError("peek from empty stack") return self._items[-1] def __len__(self): return len(self._items) def __bool__(self): return bool(self._items) s = Stack() s.push(1) s.push(2) print(s.peek()) # 2 print(s.pop()) # 2 print(len(s)) # 1 print(bool(s)) # True
A class adds the ability to attach behaviour, enforce invariants, and give the structure a clear name in the codebase. For a quick one-off, a plain list is fine.
Real use: balanced brackets
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[-1] != pairs[ch]: return False stack.pop() return not stack print(is_balanced("()")) # True print(is_balanced("([])")) # True print(is_balanced("([)]")) # False print(is_balanced("((((")) # False print(is_balanced("a(b)c[d]")) # True
This is the canonical stack problem: the most recent opening bracket must be closed first. Trying to do it without a stack means tracking nesting depth manually β which fails for mixed bracket types.
Real use: an undo stack
class Editor: def __init__(self): self.text = "" self._undo = [] def type_text(self, addition): self._undo.append(self.text) self.text += addition def undo(self): if self._undo: self.text = self._undo.pop() e = Editor() e.type_text("hello ") e.type_text("world") print(e.text) # hello world e.undo() print(e.text) # hello e.undo() print(e.text) # (empty)
Undo is naturally LIFO: the last change is the first one reversed. The stack holds previous states, and undo() pops one off.
πΆ Queues β First In, First Out
Remove from the front β but not with a list
collections.deque is the correct queue implementation. A plain list's pop(0) is O(n) because it shifts every remaining element; deque.popleft() is O(1). For small collections the difference doesn't matter, but for anything that might grow it's decisive.
from collections import deque queue = deque() queue.append("a") # enqueue queue.append("b") queue.append("c") print(queue) # deque(['a', 'b', 'c']) print(queue[0]) # 'a' β front print(queue.popleft()) # 'a' β dequeue print(queue.popleft()) # 'b' print(queue) # deque(['c']) print(len(queue)) # 1
The list-as-queue trap
# WRONG for large queues β O(n) per removal queue = [] queue.append("a") queue.append("b") queue.pop(0) # shifts every remaining element # RIGHT β O(1) per removal from collections import deque queue = deque() queue.append("a") queue.append("b") queue.popleft() # constant time
Real use: breadth-first search
from collections import deque graph = { "A": ["B", "C"], "B": ["D"], "C": ["E"], "D": [], "E": [], } def bfs(start): queue = deque([start]) visited = {start} order = [] while queue: node = queue.popleft() order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) return order print(bfs("A")) # ['A', 'B', 'C', 'D', 'E']
BFS visits nodes level by level. The queue is what enforces that order: children are added to the back, so shallower nodes are processed before deeper ones. With a stack instead, you'd get depth-first search.
π collections.deque β Double-Ended
O(1) operations at both ends
deque ("deck") supports adding and removing at both the front and the back in O(1). It's the right structure when you need stack behaviour and queue behaviour, or when you need to cap the size of a buffer.
| Operation | Complexity | Notes |
|---|---|---|
d.append(x) | O(1) | Add to the right |
d.appendleft(x) | O(1) | Add to the left |
d.pop() | O(1) | Remove from the right |
d.popleft() | O(1) | Remove from the left |
d[i] | O(n) | Random access is slow |
d.rotate(k) | O(k) | Shift elements by k positions |
Bounded buffer with maxlen
from collections import deque recent = deque(maxlen=3) for n in range(6): recent.append(n) print(list(recent))
With maxlen set, appending past the limit automatically drops the oldest item from the opposite end. This is exactly what you want for logs, histories, or fixed-size buffering.
rotate() for cyclic shifts
from collections import deque d = deque([1, 2, 3, 4, 5]) d.rotate(2) print(list(d)) # [4, 5, 1, 2, 3] d.rotate(-2) print(list(d)) # [1, 2, 3, 4, 5]
rotate(k) shifts elements right by k positions; negative k shifts left. It's handy for round-robin scheduling and cyclic buffers.
When to prefer deque over list
- You need to remove from the front efficiently
- You need a fixed-size buffer that drops old items
- You need O(1) appends at both ends
Prefer a plain list when you need fast random access by index, or when you only ever append and pop from the end.
π§΅ The queue Module β Thread-Safe
Producer/consumer patterns across threads
The queue module provides thread-safe queues. deque is not thread-safe for concurrent append and popleft from multiple threads; the queue module's Queue, LifoQueue, and PriorityQueue are.
import queue import threading q = queue.Queue() def producer(): for i in range(5): q.put(i) print(f"produced {i}") q.put(None) # sentinel to stop the consumer def consumer(): while True: item = q.get() if item is None: break print(f"consumed {item}") q.task_done() t1 = threading.Thread(target=producer) t2 = threading.Thread(target=consumer) t1.start(); t2.start() t1.join(); t2.join()
| Class | Order | Use case |
|---|---|---|
queue.Queue | FIFO | Standard producer/consumer |
queue.LifoQueue | LIFO | Thread-safe stack |
queue.PriorityQueue | Priority | Task scheduling by priority |
q.get() blocks until an item is available, and q.put() blocks when the queue is full (if a maxsize was set). This gives you backpressure for free β producers naturally slow down when consumers fall behind.
Priority queues
import queue pq = queue.PriorityQueue() pq.put((3, "low")) pq.put((1, "high")) pq.put((2, "medium")) while not pq.empty(): priority, label = pq.get() print(priority, label) # 1 high # 2 medium # 3 low
Priority items must be comparable. A common pattern is to use a tuple of (priority, value); if the values aren't comparable, add a tie-breaker like (priority, counter, value).
The alternative: heapq
import heapq heap = [] heapq.heappush(heap, 5) heapq.heappush(heap, 1) heapq.heappush(heap, 3) print(heapq.heappop(heap)) # 1 print(heapq.heappop(heap)) # 3 print(heapq.heappop(heap)) # 5
heapq is single-threaded but faster for pure priority ordering. Use it when you don't need thread safety; use queue.PriorityQueue when you do.
βοΈ Choosing the Right Structure
A decision table
| Need | Use | Why |
|---|---|---|
| Push/pop from the end only | list | Simplest and fastest for LIFO |
| FIFO with fast removal from the front | deque | O(1) popleft() |
| Add/remove at both ends | deque | O(1) at both ends |
| Fixed-size buffer | deque(maxlen=n) | Automatic eviction of old items |
| Thread-safe producer/consumer | queue.Queue | Built-in locking and blocking |
| Priority ordering | heapq or PriorityQueue | Efficient min-heap |
Complexity comparison
| Operation | list | deque |
|---|---|---|
| Append right | O(1) amortized | O(1) |
| Append left | O(n) | O(1) |
| Pop right | O(1) | O(1) |
| Pop left | O(n) | O(1) |
| Index access | O(1) | O(n) |
| Search by value | O(n) | O(n) |
deque, not a list. Everything else is a minor optimization by comparison.
ποΈ Mini Project β A Task Scheduler
Put stacks, queues, and deques together
This small program simulates a task scheduler. High-priority tasks go on a stack (most recent first), normal tasks go in a queue (oldest first), and a bounded history keeps the last few completed tasks.
from collections import deque class Scheduler: def __init__(self): self._urgent = [] # stack (LIFO) self._normal = deque() # queue (FIFO) self._history = deque(maxlen=3) # bounded log def add(self, task, urgent=False): if urgent: self._urgent.append(task) else: self._normal.append(task) def run_next(self): if self._urgent: task = self._urgent.pop() elif self._normal: task = self._normal.popleft() else: return None self._history.append(task) return task def history(self): return list(self._history) s = Scheduler() s.add("write report") s.add("reply to email") s.add("fix production bug", urgent=True) s.add("deploy hotfix", urgent=True) while True: task = s.run_next() if task is None: break print(f"ran: {task}") print("history:", s.history())
Notice the ordering: urgent tasks run in reverse insertion order (stack behaviour), normal tasks run in insertion order (queue behaviour), and the history keeps only the last three completed tasks (bounded deque). Each structure is used for the property it's actually good at.
β Frequently Asked Questions
Common questions about stacks and queues in Python
A plain list is the right choice for a stack. append() and pop() both operate on the end and are O(1) amortized, which is exactly the LIFO access pattern. There's no benefit to using deque unless you also need to add or remove from the front.
Python lists are contiguous arrays. Removing element 0 requires shifting every remaining element one position to the left, which is O(n). On a list of 1,000,000 items, every pop(0) is a million-element copy. deque.popleft() avoids this because deque is a doubly-linked list of blocks.
When multiple threads access the same queue concurrently. deque operations are individually atomic under the GIL, but combining them (e.g., "check if empty, then pop") is a race condition. queue.Queue handles locking and blocking for you, and provides get() that waits when empty.
Use heapq for a single-threaded min-heap, or queue.PriorityQueue for a thread-safe one. Both require items to be comparable, so the standard pattern is to push tuples of (priority, value). If two items have the same priority and their values aren't comparable, add an incrementing counter as a tie-breaker.
A "stack" is an abstract data structure with LIFO access. A "call stack" is the specific stack that Python's interpreter uses to track function calls β it holds return addresses and local frames. When you see RecursionError, you've exhausted the call stack. The underlying principle is the same LIFO discipline.
Yes β deque.append() and deque.pop() work just like list operations and are O(1). But it's not the idiomatic choice for a pure stack, because a list is simpler and slightly faster for append/pop only. Use deque when you need both ends.
Not for stack in the common sense β a list serves that role. For queues, collections.deque and the queue module's Queue are the standard implementations. Some third-party libraries provide richer interfaces, but the standard library covers essentially all use cases.
Check three things: (1) the consumer might be blocked on get() because nothing is being put; (2) the producer might be blocked on put() because the queue hit maxsize; (3) the sentinel value that should signal "stop" may never have been sent. queue.qsize() and logging inside both producer and consumer will show which of these is happening.
π Where to Go Next
Keep building on what you just learned