Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 60 / 101

Last in, first out. Or not..

Match the removal rule to undo histories, work queues, and traversals.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

stacks_and_queues.py
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))
↳ EXPECTED OUTPUT
undo: save
next: Build
['Test', 'Review']

03 Under the hood

  1. 1

    The stack models the most recent action as the next action to undo. It retains older actions below it.

  2. 2

    The queue processes arrivals in order. popleft avoids the repeated shifting cost of list.pop(0).

  3. 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

A SMALL MISSION

Use a deque to process three jobs in arrival order and collect their names.

Reveal one possible solution +
one_possible_solution.py
from collections import deque
jobs = deque(["A", "B", "C"])
finished = []
while jobs:
    finished.append(jobs.popleft())
print(finished)

05 Check your signal

QUICK SIGNAL CHECK

Which operation removes the oldest queued element from deque?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.