Skip to content
BENIBIX Learn

Stack (Data Structure)

Development🧮 Algorithms & Data StructuresData Structures

Also known as Stack, LIFO, Last In, First Out

A pile where the last item in is the first one out. You push and pop.

Think of it like

Think of it like a pile of plates. You add to the top, and you take from the top.

Example

Lucy types three words, then presses undo twice. The stack of changes gives back the last word, then the one before it.

Why it matters

Undo, the back button and each function call all use a stack.

Definition

A stack is a list where you can only add or remove at one end, called the top. The last item you put in is the first one out, which is called last in, first out. Adding is called push and removing is called pop. The undo button in an editor is a stack of your past changes. A program also keeps a call stack, so it knows where to return after each function.

Example code

python
>>> s = []
>>> s.append(1)
>>> s.append(2)
>>> s.pop()
2
2 went in last, so it comes out first.

Common mistake

Popping from an empty stack. Check that it has items first, or the program stops with an error.

Key takeaways

  1. 1
    Last in, first out. Like a pile of plates.
  2. 2
    Push and pop. Add and remove at the top.
  3. 3
    Everywhere. Undo, back button, function calls.

Compare