Last in, first out. Or not..
Match the removal rule to undo histories, work queues, and traversals.
01 The idea
A stack removes the newest item first; a queue removes the oldest. A Python list supports stack append/pop efficiently at the end. collections.deque supports efficient appends and removals at both ends, making it useful for queues. The access rule is part of the algorithm’s meaning: replacing a queue with a stack changes traversal order.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from collections import deque
history = []
history.append("type")
history.append("save")
print("undo:", history.pop())
queue = deque(["Build", "Test"])
queue.append("Review")
print("next:", queue.popleft())
print(list(queue))undo: save next: Build ['Test', 'Review']
03 Under the hood
- 1
The stack models the most recent action as the next action to undo. It retains older actions below it.
- 2
The queue processes arrivals in order. popleft avoids the repeated shifting cost of list.pop(0).
- 3
Check emptiness before removing, or handle IndexError when concurrent changes are possible. For coordinated multithreaded producer/consumer work, investigate queue.Queue rather than treating a deque as a complete coordination system.
04 Your turn, builder
Use a deque to process three jobs in arrival order and collect their names.
Reveal one possible solution +
from collections import deque
jobs = deque(["A", "B", "C"])
finished = []
while jobs:
finished.append(jobs.popleft())
print(finished)05 Check your signal
Which operation removes the oldest queued element from deque?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.