Stack Data Structure — LIFO, Push, Pop, Applications — Complete Beginner Guide
Learning Objectives
- Define last-in, first-out stack behavior
- Implement push, pop, and peek
- Check for empty-stack errors safely
- Read the complexity table for stacks
- Match stacks to real features like undo history
What Is a Stack?
A stack is a linear structure that lets you add and remove items from only one end, called the top. The last item you add is the first item you remove. That rule is last-in, first-out, or LIFO.
Think of a stack of trays. You place a tray on top and take the top tray off. You never pull a tray from the middle or bottom.
class Stack:
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.items.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek on empty stack")
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
s = Stack()
s.push("write email")
s.push("fix bug")
s.push("run tests")
print(s.peek()) # run tests
print(s.pop()) # run tests
print(s.pop()) # fix bug
Core Operations
| Operation | Description | Time |
|---|---|---|
| push | Add item on top | O(1) |
| pop | Remove top item | O(1) |
| peek or top | Read top item | O(1) |
| is empty | Check size | O(1) |
| search by value | May scan all items | O(n) |
Stacks are intentionally limited. Restricting access to one end keeps push and pop cheap.
How Push and Pop Work
Push writes a new value at the top index. Pop returns that value and reduces the size by one. Peek never removes anything, so you can inspect safely.
# Using a Python list as a stack
stack = []
stack.append(1) # push
stack.append(2) # push
top = stack[-1] # peek
last = stack.pop() # pop
print(top, last, stack)
Under the hood a Python list append and pop both run at amortized O(1) time because the dynamic array grows at the end.
Empty and Overflow Rules
Always check is_empty before pop or peek in production code. Raising an error on an empty stack prevents silent bugs. Overflow matters more in fixed-capacity environments such as embedded systems.
Real-World Applications
- Browser back button keeps pages in a stack
- Text editor undo history stores actions as a stack
- Function calls and local variables use a call stack
- Expression evaluation converts and computes with stacks
- Matching parentheses checks open brackets with a stack
- Depth-first graph search can use an explicit stack
Parentheses Check Example
def is_balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
openers = set(pairs.values())
stack = []
for ch in text:
if ch in openers:
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(is_balanced("(a + b) * [c - d]")) # True
print(is_balanced("(a + b")) # False
Stack versus Queue
Both are restricted linear structures. A stack removes the newest item first. A queue removes the oldest item first. Picking the wrong one scrambles your program order.
Stack Simulation Drill
Walk a short script by hand to build muscle memory. Start with an empty stack. Push alpha, push beta, push gamma. The stack from bottom to top is alpha, beta, gamma. Pop once and you remove gamma. Peek still returns beta. Push delta and the top becomes delta. Pop three times empties the stack, and the next pop must fail safely.
Translating code into this table often exposes off-by-one errors before you run anything.
| Step | Operation | Stack Bottom to Top | Result |
|---|---|---|---|
| 1 | push alpha | alpha | ok |
| 2 | push beta | alpha beta | ok |
| 3 | push gamma | alpha beta gamma | ok |
| 4 | pop | alpha beta | gamma |
| 5 | push delta | alpha beta delta | ok |
| 6 | pop pop pop | empty | delta beta alpha |
| 7 | pop | empty | error guarded |
Use the same table method for expression conversion and matching problems. If your table and your code disagree, trust the table and fix the code.
Key Takeaways
💡
- Stacks follow last-in, first-out order and expose only the top
- push, pop, and peek all run in O(1) time on a list-backed stack
- Always guard pop and peek against empty stacks
- Undo history, back buttons, and call frames are classic stack uses
- Search inside a stack is still O(n) because order is fixed
Practice Questions
- Simulate pushing A, B, then C, then popping twice. Which values remain?
- Why is pop O(1) when implemented with a Python list append and pop pattern?
- Name one application where a queue would be a better fit than a stack, and justify.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions