Skip to main content
CodeFlow
data structures~14 minRoute 02 3 of 9

The Stack

Last in, first out — a pile of pancakes you can only touch on top.

Prerequisites:Loops

Story — Stack the Pancake Chef

last in, first out

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

Push and pop. That is all I do. Push to add to the top, pop to take from the top. If you ask me to look in the middle, I'll say no.

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

Step 1 / 5python
1stack = []
2stack.append("A")
3stack.append("B")
4top = stack.pop()
5print(stack)

Quiz it — make it stick

  1. Question 1

    You push A, B, C onto a stack in that order, then pop once. What did you pop?

  2. Predict — Question 2

    What is printed?

    stack = []
    stack.append(1)
    stack.append(2)
    stack.append(3)
    stack.pop()
    stack.pop()
    print(stack)
  3. True or false — Question 3

    You can read the second-from-top element of a stack without removing the top.

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.