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.
- push with append() and pop with pop()
- Peeking at the top with [-1]
- Checking for an empty stack
"third"poppedthe last value in leaves first"second"top nowstack[-1]"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.
stack.append("third")🍽️ Put a plate on topstack.pop()⬆️ Take the top plate offstack[-1]👀 Look at the top plate without taking itstack📚 The plates still on the pileA stack is a last-in, first-out (LIFO) collection: items are added and removed only at the top.
Key points
stack.append(...)pushes an item onto the top, which is the end of the list.stack.pop()removes and returns the top item, here"third".stack[-1]reads the top item without removing it.- Both
appendandpopwork 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
stack = []
stack.append("first")
stack.append("second")
stack.append("third")
print("popped:", stack.pop())
print("top:", stack[-1])
print("stack:", stack)
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.
- Try empty, single-item, and duplicate-value inputs.
- Print state after every step to observe the algorithm.
- Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Common mistakes
Popping from an empty stack
pop() on an empty list raises IndexError.
item = stack.pop()
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.
stack.insert(0, item)
stack.pop(0)
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.
- Nearest Smaller Value to the Left For each number, find the closest earlier position containing a strictly smaller number. Medium
- Mini Stack-Language Interpreter Evaluate a small stack language. Hard