Stacks: The Pancake Pile
Stacks: The Pancake Pile 🥞
No new syntax today — just a new IDEA, and it's a famous one.
A stack is a pile where you only ever touch the TOP. Pancakes, plates, browser history, the undo button: all stacks. In Python, a plain list plays the part perfectly, as long as you only use two moves:
pile = []
pile.append("pancake") # push: put on top
top = pile.pop() # pop: take the top off
pile[-1] # peek: look, don't touch
The rule this creates is called last in, first out: the newest thing is always the first to leave. That one rule turns out to solve a shocking number of puzzles:
- Reversal — push everything, pop everything: order flips.
- Undo — the thing to cancel is always the most recent one.
- Matching — every closing bracket pairs with the most recent open one.
- Backtracking — retreat exactly one step: pop a breadcrumb.
One safety habit before you start: never pop an empty pile. Check len(pile) > 0 first — Python crashes on an empty pop, and so do vending machines.
By the end of this unit you'll have built an undo/redo system, a bracket inspector, a train switch yard, and a tiny backwards calculator — all from one list and two moves. Stack 'em up!