Python Algorithms

Stack Data Structure in Python

Last in, first out: use a list as a stack with append, pop and [-1], the structure behind undo and function calls.

  • Intermediate
  • 2 min read
  • 1 runnable example
What you'll learn
  • push with append() and pop with pop()
  • Peeking at the top with [-1]
  • Checking for an empty stack
append first, second, third; then pop()
  1. "third"poppedthe last value in leaves first
  2. "second"top nowstack[-1]
  3. "first"bottom

Only the top is reachable

The problem

Undo buttons, the back button in a browser and checking matching brackets all need to remember items and take back the most recent one first. A stack is the data structure built exactly for that.

Think of it like this

A stack is like a pile of plates in a cafeteria. You put new plates on top and take plates from the top. The last plate added is the first one used, and you cannot pull out a plate from the middle.

From a pile of plates to code
stack.append("third")🍽️ Put a plate on top
stack.pop()⬆️ Take the top plate off
stack[-1]👀 Look at the top plate without taking it
stack📚 The plates still on the pile
Last in, first out: only the top is reachable.
In one sentence

A stack is a last-in, first-out (LIFO) collection: items are added and removed only at the top.

Key points

  1. stack.append(...) pushes an item onto the top, which is the end of the list.
  2. stack.pop() removes and returns the top item, here "third".
  3. stack[-1] reads the top item without removing it.
  4. Both append and pop work at the end of the list, so they are fast.

When should you use it?

  • Undo and redo histories.
  • Checking matching brackets and parsing expressions.
  • Depth-first search and backtracking without recursion.

When not to use it

  • Items must leave in the order they arrived: that is a queue.
  • You need items from the middle or by position: a normal list or another structure fits better.

See how it works

Push and pop to see that the last item in is always the first one out.

Example code

Run code →
main.py
stack = []
stack.append("first")
stack.append("second")
stack.append("third")

print("popped:", stack.pop())
print("top:", stack[-1])
print("stack:", stack)
Get a Run button for this example

Result of running the code

popped: third
top: second
stack: ['first', 'second']

Code explanation

List append pushes onto the top and pop removes from the same end. Both operations are O(1) amortized.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Try empty, single-item, and duplicate-value inputs.
  2. Print state after every step to observe the algorithm.
  3. Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Run in the Python compiler →

Common mistakes

Popping from an empty stack

pop() on an empty list raises IndexError.

Problem
item = stack.pop()
Fix
if stack:
    item = stack.pop()

Using the front of the list as the top

insert(0, x) and pop(0) move every item, which is slow.

Problem
stack.insert(0, item)
stack.pop(0)
Fix
stack.append(item)
stack.pop()

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges