Stack programs
Part of the free LogicWiz Python course, Pack A: CBSE Class 12 Board Pack. The examples and practice run in the app.
In the canteen, Shankar bhaiya stacks clean plates one on top of another. The last plate he puts down is the first one a student picks up. That is a stack, and it is a sure-shot 3-mark question in your board paper.
You'll learn to
- Explain LIFO and build a stack on a Python list
- Write push, pop, peek and display with an empty check
- Solve the board question: push items that meet a condition, then pop and display
Learn
LIFO: last in, first out
A stack lets you add and remove items at one end only, the top. The last item in is the first item out (LIFO).
On a Python list, the top is the end of the list:
| Operation | Python |
|---|---|
| push x | stack.append(x) |
| pop | stack.pop() |
| peek (see top) | stack[-1] |
| is it empty? | len(stack) == 0 or not stack |
Popping an empty stack is called underflow.
Push three, pop one
stack = []
stack.append("idli")
stack.append("dosa")
stack.append("vada")
print(stack)
top = stack.pop()
print("Popped:", top)
print("Top now:", stack[-1])
print(stack)
Step through it and watch the list grow at the right end and shrink from the same end.
A complete stack with an underflow check
def push(stack, item):
stack.append(item)
def pop(stack):
if len(stack) == 0: # underflow check
return "Underflow"
return stack.pop()
def peek(stack):
if not stack:
return "Empty"
return stack[-1]
def display(stack):
for item in stack[::-1]: # top first
print(item)
plates = []
push(plates, "steel plate")
push(plates, "paper plate")
push(plates, "banana leaf")
display(plates)
print("Peek:", peek(plates))
for i in range(4):
print("Pop:", pop(plates))
This is the "implement a stack using a list" program from the CBSE practical list.
pop() on an empty list crashes with IndexError: pop from empty list. Always check if stack: (or len(stack) == 0) first.
And pop(0) is not a stack pop: it removes the bottom item, which makes your stack behave like a queue.
The 3-mark question: push with a condition
players = [("Rohit", 76), ("Gill", 12), ("Virat", 54), ("Pant", 49), ("Rahul", 101)]
Fifty = []
def Push_fifty():
for p in players:
if p[1] >= 50: # condition on the runs
Fifty.append(p)
print(Fifty)
def Pop_fifty():
while len(Fifty) > 0:
print(Fifty.pop())
print("Stack Empty")
Push_fifty()
Pop_fifty()
Each item is a tuple, so the condition looks at p[1] (the runs), but the whole tuple is pushed.
Variant: push from a dictionary
stock = {"Maggi": 4, "Parle-G": 25, "Frooti": 8, "Lays": 15, "Bourbon": 3}
REORDER = []
def push_low(d):
for item in d:
if d[item] < 10:
REORDER.append(item)
def pop_low():
while REORDER:
print(REORDER.pop(), end=" ")
print()
print("Stack Empty")
push_low(stock)
print(REORDER)
pop_low()
Looping over a dict gives its keys; d[item] is the value. Other variants push even numbers, words starting with a vowel, or names with marks above 75.
How the 3 marks split: about 1.5 for push (loop, condition, append) and 1.5 for pop (empty check, pop(), display, the "Stack Empty" message). Use the exact function and stack names from the question. Keeping the stack as a global list or passing it as a parameter are both accepted.
In one line
A stack is LIFO: push with append(), pop with pop(), peek with [-1], and always check for an empty stack before popping.