Module 5 · Stacks, Queues and Linked Lists · Lesson 14 of 40
Stacks: last in, first out
A pile where you add and remove only at the top. Used for undo, brackets and the function call stack.
In this lesson · about 20 minutes
- Use a Python list as a stack with append and pop
- Explain LIFO with an everyday example
- Check whether brackets are balanced
A stack is like a pile of plates. You put a plate on the top, and you take a plate from the top. The last plate you added is the first one you take off. This rule is called LIFO: Last In, First Out.
| Action | Meaning | Python list | Cost |
|---|---|---|---|
| push | Add to the top | stack.append(x) | O(1) |
| pop | Remove from the top | stack.pop() | O(1) |
| peek | Look at the top | stack[-1] | O(1) |
| is empty? | Nothing left? | not stack | O(1) |
Popping an empty stack is an error called underflow. Always check if stack: first.
Where stacks appear
- The Undo button: the last change is undone first.
- The browser's Back button.
- Function calls: Python keeps waiting calls on a call stack.
- Checking brackets in code or maths.
Try it · see it work
Stack vs queue
For now, look at the stack on the left. Add a few letters, then pop. Which comes out first?
Stack (LIFO), like a pile of plates
Queue (FIFO), like a line at a shop
Add the same items to both, then remove one from each. Which item leaves first?
Balanced brackets
Is "( [ ] { } )" balanced? Yes. Is "( ]"? No. A stack solves this neatly:
- When you see an opening bracket
( [ {, push it. - When you see a closing bracket, the top of the stack must be its partner. If it is, pop it. If not (or the stack is empty), the brackets are not balanced.
- At the end, the stack must be empty.
Try it: a stack in action
Exercise
Balanced brackets
Write is_balanced(s) that returns True if every bracket in s is closed in the right order. Only the characters ()[]{} appear.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.