Skip to content
dreamcode
dreamcode
Map
Stacks & queues
Lesson 60 of 77
+15 XP on finish
ALGORITHMSChapter 10 · Algorithms and Problem Solving

Stacks and queues

A stack is last in, first out, like a pile of plates: push with .append() and pop with .pop(). A queue is first in, first out, like a line of people: use collections.deque, add with .append() and remove from the front with .popleft(), which is fast (unlike list.pop(0)). Stacks power undo and bracket matching; queues schedule work in order.

Worked example

How it reads

  • stack.pop() takes the most recent item: the last thing done is the first undone
  • queue.popleft() takes the oldest item: first come, first served
  • deque adds and removes at both ends in O(1)
Cloud tip: Whenever something must be matched in reverse order (brackets, tags, undo), think stack.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Finish balanced with the stack so it prints True, False, False.

Press Run to check your work.