Skip to content

Module 18 · Algorithms and Problem Solving — topic 14 of 18

Stacks

The last-in, first-out (LIFO) data structure: push, pop and peek with Python lists, a Stack class, checking balanced brackets, evaluating postfix expressions, and undo history.

Beginner 10 min read·Lesson 274 of 306 in Python Programming

Learning objectives

  • Use a list as a stack
  • Write a Stack class with push, pop and peek
  • Solve bracket-matching and expression problems with stacks

Definition

A stack is a collection where items are added and removed at the same end, the top. The last item pushed is the first popped: last in, first out (LIFO).

Introduction

A pile of plates, the browser back button and the undo feature in an editor all work like stacks: the most recent item comes off first.

Why it matters

Stacks solve many problems elegantly — matching brackets, evaluating expressions, backtracking — and explain how function calls work.

Detailed explanation

push adds an item to the top; pop removes and returns the top item; peek looks at the top without removing it.

A Python list is an efficient stack: append is push, pop() is pop, and items[-1] is peek — all O(1).

Popping an empty stack is an error; check with if stack: or handle IndexError.

Wrapping the list in a class gives a clear interface and a meaningful error message.

Bracket matching: push each opening bracket; for each closing bracket, pop and check it matches. The text is balanced if every check passes and the stack ends empty.

Postfix (reverse Polish) expressions such as 3 4 + 2 * are evaluated by pushing numbers and, for each operator, popping two operands and pushing the result.

Undo history pushes a snapshot or reverse action before each change and pops to undo.

Python itself uses a call stack: each function call is pushed and popped when it returns — which is why deep recursion can overflow it.

Syntax

Python
stack = []
stack.append("a") # push
top = stack[-1] # peek
item = stack.pop() # pop
  • LIFO: last in, first out.
  • Lists make efficient stacks.
  • Check for empty before popping.

Code examples

A list as a stack

Python
stack = []
for item in ["a", "b", "c"]:
stack.append(item)
print(stack.pop(), stack.pop(), stack, stack[-1])
Output
c b ['a'] a

Balanced brackets

Python
def balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print([balanced(t) for t in ["(a[b]{c})", "(]", "((", "print('hi')"]])
Output
[True, False, False, True]

More examples

A Stack class, postfix evaluation and undo

Python
import operator
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
return self._items[-1] if self._items else None
def __len__(self):
return len(self._items)
OPS = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}
def eval_postfix(expr):
s = Stack()
for token in expr.split():
if token in OPS:
b, a = s.pop(), s.pop()
s.push(OPS[token](a, b))
else:
s.push(float(token))
return s.pop()
print(eval_postfix("3 4 + 2 *"), eval_postfix("5 1 2 + 4 * + 3 -"))
text, history = [], Stack()
for word in ["Hello", "big", "world"]:
history.push(list(text))
text.append(word)
text = history.pop()
print(" ".join(text), len(history))
try:
Stack().pop()
except IndexError as e:
print(e)
Output
14.0 14.0
Hello big 2
pop from empty stack

Step-by-step explanation

  • For each operator, the two most recent numbers are popped — the second pop is the left operand.
  • Before each word is added, a snapshot of the text is pushed, so one pop undoes the last change.
  • The class raises a clear error when popping an empty stack.

Expected output

Running “A Stack class, postfix evaluation and undo” prints exactly:

TextOutput
14.0 14.0
Hello big 2
pop from empty stack

Practical applications

  • Undo in editors and browser back buttons.
  • Syntax checking in compilers and code editors.

Best practices

  • Use list append/pop for stacks.
  • Check for empty stacks.
  • Wrap in a class when the meaning should be explicit.

Common mistakes

Popping from the front

Avoid

stack.pop(0)

Prefer

stack.pop()

pop(0) removes the oldest item (queue behaviour) and is O(n).

Important notes

  • collections.deque also works as a stack and is thread-friendly for appends and pops at both ends.

Key takeaways

  • Stacks are LIFO: push and pop at the top.
  • Lists implement stacks efficiently.
  • Used for brackets, expressions, undo and the call stack.

Try it yourself

  1. 1
    Reverse a string using a stack.
  2. 2
    Implement browser back and forward buttons with two stacks.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic