Stacks

Lesson 11 of 20

Watch a Python list act as a LIFO stack — undo rewinds, brackets balance and a monotonic stack sweeps Next Greater Element.

The big picture

Meet the stack

A stack touches only its top. Whatever went in last comes out first — the rule behind undo, back buttons and every function call your interpreter makes.

LIFO rule

Push 12 then 7, and the first pop hands back 7. The newest value always leaves first.

A list is a stack

append() pushes onto the top, pop() removes the last item — both O(1). No new class needed.

Peek and underflow

stack[-1] reads the top without removing it. Popping an empty list raises IndexError — stack underflow, Python style.

Where you meet it

Undo history, browser back, matching brackets, the call stack and depth-first search all run on stacks.

The faster cousin

collections.deque gives O(1) append and pop on both ends — the hot-loop choice when a list would copy.