Stacks and queues: who goes next?
A robot cell gets jobs faster than it can do them. Do you serve the newest job first, or the oldest? The answer changes everything.
About 35 min · 3 goals · Checked by automated tests
1.Why should I care?
Many systems are really about order: undo histories, job queues, sensor event buffers, and the search frontier of a path planner. A stack serves the newest item first (LIFO); a queue serves the oldest (FIFO). Picking the wrong one is a fairness bug, or a planner that wanders.
- ◇ Use a list as a stack (append/pop) and collections.deque as a queue (append/popleft).
- ◇ Trace the contents of a stack or queue through a sequence of operations.
- ◇ Choose last-in-first-out or first-in-first-out for an engineering task and justify it.
2.Discover
In Stack mode, append three values and pop twice: which came out? Do the same sequence in Queue mode. Then pop from an empty structure and read the error. Which one would you use for an undo button, and which for print jobs?
Loading the interactive…
Can't use the interactive? Read a description instead
The stack and queue modes show items in a row, oldest on the left. In a stack, append adds to the right and pop removes from the right (newest). In a queue, append adds to the right and popleft removes from the left (oldest). Popping from an empty structure shows IndexError.
3.Checkpoint: guided practice
Check what you just discovered before going on. Hints appear after a wrong answer.
Practice 1 · a fresh version every time
A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(27); q.append(49); q.popleft(); q.append(37); q.popleft(). What value does the final q.popleft() return?
4.Predict
A queue receives jobs 101, 102, 103, then serves one job, then receives 104. Which job is served next?
Guess first. Being wrong here is how the surprise works.
5.Understand
Stack: last in, first out
A Python list is a stack: s.append(x) pushes onto the top, s.pop() removes and returns the top. Both are fast (O(1)). Use it for undo, for backtracking, and for depth-first search.
Queue: first in, first out
from collections import deque gives a double-ended queue. q.append(x) joins the back; q.popleft() serves the front, both in O(1). Don't use list.pop(0) for a queue: it shifts every remaining item, which is O(n).
Empty means stop
Popping from an empty list or deque raises IndexError. Loops usually run while q: (an empty container is falsy), so they end naturally when the work is done.
Explain it another way
A stack is a pile of plates: you take the top one. A queue is a line at a bus stop: the person who arrived first boards first.
deque is implemented as a linked list of blocks, so both ends are O(1). A list is a dynamic array: the end is O(1) amortised, but inserting or removing at the front moves every element.
Robot task schedulers use FIFO queues for fairness; motion planners use stacks to backtrack out of dead ends; breadth-first search (next lesson) is simply 'keep the frontier in a queue'.
Worked example 1
Process jobs in arrival order and keep an undo history.
from collections import deque
jobs = deque()
for job in ["drill A", "drill B", "inspect A"]:
jobs.append(job)
print(jobs.popleft()) # drill A (oldest first)
jobs.append("drill C")
print(list(jobs)) # ['drill B', 'inspect A', 'drill C']
undo = []
undo.append("move wp3")
undo.append("delete wp5")
print(undo.pop()) # delete wp5 (newest first)
while jobs: # stops when the queue is empty
print("doing", jobs.popleft())Common mix-ups
- A list works fine as a queue.
✓ It works, but list.pop(0) is O(n). deque gives O(1) at both ends. - Stacks and queues are different kinds of storage.
✓ They are the same items with different rules about which one leaves next.
6.Watch
→ Watch for the two operations each structure allows and which end of the line they use.
Contrasts last-in-first-out with first-in-first-out using clear diagrams, the two orders behind undo and job queues.
Length: see YouTube · captions on YouTube · source
Nothing loads from YouTube until you press play.
The video is optional: everything you need is also in the lesson text and the interactive.
7.Practice on your own
Practice, not a test. Wrong answers get a hint and another try.
Practice 2
An editor's undo button should reverse the most recent change first. Which structure?
Practice 3
Why use deque.popleft() instead of list.pop(0) for a long job queue?
Practice 4 · a fresh version every time
An editor keeps an undo stack of waypoint ids: s = []; s.append(38); s.append(23); s.append(27); s.pop(); s.append(33); s.pop(); s.append(3); s.pop(). What value does the final s.pop() return?
Practice 5
What does 'while q:' do when q is an empty deque?
8.Apply it
Simulate a robot cell: jobs arrive at known times and each takes a known number of minutes. Use a deque to serve them in order and record each job's waiting time. Then try a stack instead and compare the longest wait. Which is fairer, and when might the stack be acceptable?
9.Reflect
10.Go further
- Python docs: collections.deque ↗All deque operations and their costs, including maxlen for fixed-size buffers.
Concepts: Lists, dictionaries and tabular data