Stacks (LIFO)

Push and pop from the top — last in, first out. The same rule runs the call stack: each function call pushes a frame; each return pops it.

Data structures Beginner LIFO · Call stack ~8 min
The idea

Last in, first out

Think of a stack of plates: you put a new plate on top, and you take from the top. You never slide one out of the middle.

When a program calls a function, the computer pushes a stack frame (locals and where to return). A nested call pushes another frame on top. When a function finishes, its frame pops — the caller underneath becomes active again. That is LIFO in action.

TipOnly the top frame runs. Waiting callers sit below until the top returns.
IdeaCall then return
call_stack.pyPython
def add(a, b):
    return a + b

def double(n):
    return add(n, n)

print(double(4))  # → 8

double waits while add runs on top of the call stack.

Interactive

Run the simulation

First push and pop values. Then watch stack frames grow and shrink as nested calls run.

Step 0 / 0
demo.pyPython
Stack + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Try it yourself

Push and pop freely

Build your own value stack. Push adds on top; pop removes from the top.

Ready
Stack is empty. Enter a value and press Push.
Remember

Stack mental model

Restrict access to one end — values and call frames both use LIFO.

LIFO

Last in, first out

Pop always returns the most recently pushed value or frame.

Frames

Call → push, return → pop

Each call adds a frame with locals. The return pops that frame and resumes the caller.

Next

Recursion uses the same stack

See many frames of one function in the factorial simulation.