The Stack
Last in, first out — a pile of pancakes you can only touch on top.
Prerequisites:Loops
Story — Stack the Pancake Chef
Meet Stack the Pancake Chef. Stack has one rule: pancakes go on the top of the plate, and the only pancake you can take is the one on top. There is no reaching into the middle.
That rule has a name: LIFO — last in, first out. The last pancake added is the first one taken. Every stack in programming, anywhere, follows this rule.
Stack says
See it — push, pop, peek
Type a value and press Push, or click Pop to remove the top. Try popping from an empty stack to see what happens.
Try it — predict the order
Exercise. Push A, B, C, D in that order. Pop twice, then push E. Pop everything one at a time and write down the order in which the values come out.
Reveal answer at the bottom of this section.
Reveal answer
After pushing A,B,C,D the stack is [A, B, C, D]. Two pops remove D and C. Push E gives [A, B, E]. Popping everything yields E, B, A.
Code it — five languages, one idea
stack = []
stack.append("A")
stack.append("B")
top = stack.pop() # "B"
print(stack) # ["A"]Walk through it line by line
1stack = []2stack.append("A")3stack.append("B")4top = stack.pop()5print(stack)
Quiz it — make it stick
No Dumb Questions
Real questions other learners asked on this page.
How is a stack different from a list or array?
A stack is a discipline, not a different storage. It says: only touch the top. A Python list is a stack when you only ever use append() and pop(); it is something else when you use insert(0, …). The discipline is the data structure.Where do real programs use stacks?
Every time you call a function. The computer keeps a stack of "what was I doing before this call?" so it can return to the right place. That is the call stack. Editors use a stack for undo. Browsers use a stack for back-button history.What happens if I pop from an empty stack?
In most languages an exception is thrown — "underflow." Some languages return a sentinel (Python raises IndexError; JavaScript returns undefined). Always either check the size first or wrap in a try/except.