Chapter 3: Stacks in Python ๐¶
Mentor's Note: A Stack is one of the most fundamental structures in computer science. Every time you press "Undo" (Ctrl+Z) or hit the "Back" button in your browser, you are using a Stack! ๐ก
๐ The Scenario: The Pizza Box Stack ๐¶
Imagine you are at a pizza delivery hub in Surat.
- The Logic: As new pizzas come out of the oven, they are stacked one on top of the other. ๐ฆ
- The Rule: You can only take the Top box. To get to the bottom box, you must first remove all the ones above it. ๐ฆ
- The Result: This is LIFO (Last In, First Out). The last pizza placed on the stack is the first one to be delivered. โ
๐ Concept Explanation¶
1. What is a Stack?¶
A stack is a linear data structure that follows the principle of Last In, First Out (LIFO).
2. Core Operations ๐ ๏ธ¶
| Operation | Logic | Python Method |
|---|---|---|
| PUSH | Add an item to the top. | .append() |
| POP | Remove the top item. | .pop() |
| PEEK | Look at the top item without removing it. | stack[-1] |
| isEmpty | Check if the stack is empty. | len(stack) == 0 |
๐จ Visual Logic: LIFO in Action¶
graph TD
A[Bottom] --- B[Middle]
B --- C[TOP ๐]
D[New Item] -- PUSH --> C
C -- POP --> E[Removed Item]
๐ป Implementation: The Stack Lab¶
# ๐ Scenario: Managing a stack of boxes
# ๐ Action: Implementing PUSH and POP
def push(stack, item):
stack.append(item)
print(f"Pushed: {item} ๐ฅ")
def pop(stack):
if len(stack) == 0:
print("Underflow! Stack is empty. โ")
return None
return stack.pop()
# ๐๏ธ Testing the stack
my_stack = []
push(my_stack, "Box 1")
push(my_stack, "Box 2")
removed = pop(my_stack)
print(f"Removed: {removed} ๐ค")
# ๐๏ธ Outcome: Prints "Removed: Box 2" (LIFO)
๐ Sample Dry Run¶
| Step | Operation | Stack State | Result |
|---|---|---|---|
| 1 | push(10) |
[10] |
10 is at Top |
| 2 | push(20) |
[10, 20] |
20 is at Top |
| 3 | pop() |
[10] |
20 is removed! โ |
๐ Technical Analysis¶
- Underflow: Trying to
popfrom an empty stack. โ ๏ธ - Overflow: Trying to
pushinto a stack that has no more memory (rare in Python).
๐ฏ Practice Lab ๐งช¶
Task: The String Reverser
Task: Use a stack to reverse a string (e.g., "HELLO" -> "OLLEH"). Hint: Push each letter into a stack, then pop them all out! ๐ก
๐ก Board Exam Focus (CBSE Class 12) ๐¶
- Important: You will likely have to write a complete Python script including
push()andpop()functions for 3-5 marks. Practice the "Underflow" check!
๐ก Pro Tip: "A stack is not just a data structure; it's a way of looking at the world. Last in, first out!" - Anonymous