Stacks Explained With Real Examples
A stack is a data structure where the last item added is the first item removed. This is called **last in, first out**, or **LIFO**. The easiest mental model is a stack of plates. If you put a plate on top, that plate is the first one you can take off. You do not usually pull a plate from the middle. Stacks are simple, but they show up in many important places:
- undo and redo features
- browser history
- function calls
- parsing expressions
- matching parentheses
- depth-first search Once you recognize the pattern, stacks become one of the most useful tools in basic problem solving.
The Mental Model
A stack usually has two main operations:
| Operation | Meaning |
| --- | --- |
| Push | Add an item to the top |
| Pop | Remove the item from the top |
You may also see:
| Operation | Meaning |
| --- | --- |
| Peek | Look at the top item without removing it |
| Is empty | Check whether the stack has no items |
The important rule is that only the top item is directly accessible. ```plain text top -> "third" "second" "first"
If we pop from this stack, \`"third"\` comes out first.
## A Small Python Example
Python lists can be used as stacks.
```python
stack = []
stack.append("first")
stack.append("second")
stack.append("third")
print(stack.pop()) # third
print(stack.pop()) # second
print(stack.pop()) # first
In this example:
- `append` pushes an item onto the stack
- `pop` removes the most recent item The last item added was `"third"`, so it is the first item removed.
Why Stacks Are Useful
Stacks are useful when the most recent thing matters first. That sounds narrow, but it appears constantly. Imagine an undo feature in a text editor. Every time the user does something, you push that action onto a stack:
undo_stack = []
undo_stack.append("typed hello")
undo_stack.append("made text bold")
undo_stack.append("deleted paragraph")
If the user presses undo, the most recent action should be reversed first:
last_action = undo_stack.pop()
print(last_action) # deleted paragraph
That is stack behavior.
Valid Parentheses Example
One classic stack problem is checking whether parentheses are balanced.
def is_valid_parentheses(text):
stack = []
pairs = {
")": "(",
"]": "[",
"}": "{",
}
for char in text:
if char in "([{":
stack.append(char)
elif char in ")]}":
if not stack:
return False
if stack.pop() != pairs[char]:
return False
return len(stack) == 0
Example:
print(is_valid_parentheses("([])")) # True
print(is_valid_parentheses("([)]")) # False
The stack keeps track of opening brackets. When we see a closing bracket, it must match the most recent opening bracket. That “most recent thing must be handled first” rule is exactly what stacks are good at.
The Call Stack
Stacks are not just a data structure you create manually. Your programming language uses a stack internally for function calls.
def first():
second()
def second():
third()
def third():
print("done")
first()
The calls stack up like this: ```plain text third() second() first()
When \`third\` finishes, control returns to \`second\`. When \`second\` finishes, control returns to \`first\`.
This is called the call stack.
Understanding the call stack makes recursion much easier to understand later.
## Common Mistakes
### Mistake 1: Confusing stacks and queues
A stack is last in, first out.
A queue is first in, first out.
If the newest item should be handled first, think stack.
If the oldest item should be handled first, think queue.
### Mistake 2: Popping from an empty stack
This will raise an error:
```python
stack = []
stack.pop()
Check whether the stack has items before popping when empty stacks are possible.
if stack:
item = stack.pop()
Mistake 3: Using a stack when order should be preserved
Stacks reverse the order of removal. If you add `first`, `second`, and `third`, you get `third`, `second`, and `first` back. That is useful for some problems and wrong for others.
Where This Shows Up in Real Projects
Stacks appear in:
- undo history
- navigation history
- parsing nested syntax
- validating brackets
- recursive function calls
- depth-first traversal
- backtracking algorithms You may not always call the structure a stack, but the behavior is common. If your problem says “handle the most recent item first,” there is a good chance a stack fits.
Key Takeaways
- A stack is last in, first out.
- Push adds to the top.
- Pop removes from the top.
- Stacks are useful when the newest item should be handled first.
- Python lists can work as simple stacks.
The call stack is one of the most important real examples.
Related Articles
Queues Explained With Real Examples
- Recursion Explained With Simple Examples
- Linked Lists Explained From Scratch