Stacks
What is a Stack?
A stack is a linear data structure that follows the LIFO principle —Last In, First Out.
This means the last element added (pushed) into the stack will be the first one removed
(popped).
Operations on Stack
Operation Description
Push Adds an element to the top of the stack
Pop Removes and returns the top element of the stack
Peek or Top Returns the top element without removing it
isEmpty Checks if the stack is empty
Stack Implementation using List in Python
1. Creating a Stack
You can use a list in Python to represent a stack.
stack = [] # Empty stack
2. Push Operation
Use the .append() method to push an element:
stack.append(10)
stack.append(20)
print("Stack:", stack) # Output: [10, 20]
3. Pop Operation
Use the .pop() method to pop the top element:
top = stack.pop()
print("Popped element:", top) # Output: 20
print("Stack now:", stack) # Output: [10]
4. Peek Operation (View top without removing)
if stack:
print("Top element:", stack[-1]) # Output: 10
5. Check if Stack is Empty
if not stack:
print("Stack is empty")
else:
print("Stack is not empty")
Example Program (Push & Pop)
stack = []
# Push elements
stack.append("A")
stack.append("B")
stack.append("C")
# Pop elements
print("Popped:", stack.pop()) # C
print("Popped:", stack.pop()) # B
print("Stack now:", stack) # ['A']
Applications of Stack
Application Use
Undo feature In text editors or drawing apps
Backtracking In games or puzzles (like Sudoku)
Function calls Managed using stack (call stack)
Expression evaluation Converting infix to postfix and evaluating expressions
Balanced parentheses checking Using stack to validate brackets (), {}
Stack: Overflow and Underflow
In a stack data structure, two common exceptional conditions can occur:
1. Stack Overflow: Overflow occurs when we try to push (add) an element into a full stack.
Example (Fixed Size Stack):
MAX_SIZE = 3
stack = []
def push(item):
if len(stack) >= MAX_SIZE:
print("Stack Overflow")
else:
stack.append(item)
# Example usage
push(10)
push(20)
push(30)
push(40) # This will give "Stack Overflow"
2. Stack Underflow: Underflow occurs when we try to pop (remove) an element from an
empty stack.
Example:
stack = []
def pop():
if not stack:
print("Stack Underflow")
else:
print("Popped:", stack.pop())
# Example usage
pop() # This will give "Stack Underflow"
Q Write a function in Python POPSTACK (L) where L is a stack implemented by a list of
numbers. The function returns the value deleted from the stack.
Ans
def POPSTACK(L):
if len(L) == 0:
return "Stack Underflow - Cannot pop from empty stack"
else:
return L.pop()
stack = [10, 20, 30, 40]
print("Before POP:", stack)
deleted_value = POPSTACK(stack)
print("Deleted value:", deleted_value)
print("After POP:", stack)
OutPut:
Before POP: [10, 20, 30, 40]
Deleted value: 40
After POP: [10, 20, 30]
Q A list contains following record of a customer:
[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack named
‘status’: (i) Push_element() - To Push an object containing name and Phone number of
customers who live in Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also, display “Stack
Empty” when there are no elements in the stack.
For example:
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
The output should be:
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”] Stack Empty
Ans
We have:
A list of customer records: [Name, Phone, City]
A stack named status to store only [Name, Phone] of customers from Goa
We need to write:
o Push_element() → push records from Goa into status
o Pop_element() → pop and display records from status, showing "Stack Empty" at
the end
status = [] # Stack to store filtered customer data
# List of customer records
customers = [
["Gurdas", "99999999999", "Goa"],
["Julee", "8888888888", "Mumbai"],
["Murugan", "77777777777", "Cochin"],
["Ashmit", "1010101010", "Goa"]
]
# Function to push Goa customers to stack
def Push_element():
for record in customers:
if record[2] == "Goa":
status.append([record[0], record[1]])
# Function to pop elements from stack and display them
def Pop_element():
while status:
print(status.pop())
print("Stack Empty")
# Calling the functions
Push_element()
Pop_element()
Output:
['Ashmit', '1010101010']
['Gurdas', '99999999999']
Stack Empty
Q Write a function in Python, Push(SItem) where , SItem is a dictionary containing the details
of stationery items– {Sname:price}.
The function should push the names of those items in the stack who have price greater than
75.
Also display the count of elements pushed into the stack.
For example: If the dictionary contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}
The stack should contain:
Notebook Pen
Ans
Problem Requirements:
Input: A dictionary SItem in the form {Sname: price}
Task:
o Push names of items with price > 75 into a stack
o Display the names in the stack
o Show the count of items pushed
def Push(SItem):
stack = []
for item, price in SItem.items():
if price > 75:
stack.append(item)
# Display the stack contents
for element in reversed(stack): # Optional: To show last pushed first (top of stack)
print(element)
# Display count of pushed elements
print("Count of items pushed:", len(stack))
# Example usage:
Ditem = {"Pen": 106, "Pencil": 59, "Notebook": 80, "Eraser": 25}
Push(Ditem)
Output:
Notebook
Pen
Count of items pushed: 2
Q Create a stack that stores dictionaries as elements.
Each dictionary represents a person's information ( name, age, city).
Implement a `push_dict` method to push a dictionary onto the stack of person above age 20
Implement a `pop_dict` method to pop the top dictionary from the stack.
Ans
Each dictionary contains a person's information: {"name": ___, "age":__, "city":__}
Only people with age > 20 are pushed onto the stack.
The stack behaves in LIFO order.
# Stack to store dictionaries
person_stack = []
# Function to push dictionary onto stack if age > 20
def push_dict(person):
if person["age"] > 20:
person_stack.append(person)
# Function to pop dictionary from top of the stack
def pop_dict():
if len(person_stack) == 0:
print("Stack is empty.")
else:
popped = person_stack.pop()
print("Popped:", popped)
# Example usage
push_dict({"name": "Alice", "age": 25, "city": "Delhi"})
push_dict({"name": "Bob", "age": 18, "city": "Mumbai"}) # Will not be pushed
push_dict({"name": "Charlie", "age": 30, "city": "Goa"})
# Popping from the stack
pop_dict() # Pops Charlie
pop_dict() # Pops Alice
pop_dict() # Stack is empty
Q Create a stack to manage student records. Each student record is represented as a
dictionary containing attributes like student ID, name, and GPA.
Implement a `push_student` method to push student records onto the stack that GPA above
60.
Implement a `pop_student` method to pop the top student record from the stack
Ans
Push only if GPA > 60
Use push_student() to add a student
Use pop_student() to remove and display the top record
# Stack to store student records
student_stack = []
# Function to push student record if GPA > 60
def push_student(student):
if student["GPA"] > 60:
student_stack.append(student)
# Function to pop top student record from stack
def pop_student():
if len(student_stack) == 0:
print("Stack is empty.")
else:
popped = student_stack.pop()
print("Popped Student Record:", popped)
# Example usage
push_student({"student_id": "S101", "name": "Ananya", "GPA": 78})
push_student({"student_id": "S102", "name": "Ravi", "GPA": 59}) # Will not be pushed
push_student({"student_id": "S103", "name": "Meera", "GPA": 88})
# Pop student records
pop_student() # Pops Meera
pop_student() # Pops Ananya
pop_student() # Stack is empty
Output:
Popped Student Record: {'student_id': 'S103', 'name': 'Meera', 'GPA': 88}
Popped Student Record: {'student_id': 'S101', 'name': 'Ananya', 'GPA': 78}
Stack is empty.
Q Assume a nested dictionary .
Each dictionary can contain other dictionaries as values.
The format of the dictionary is as follows: {1:{‘a’:’one,’b’:’two},2:{‘x’:10},3:{‘y’:100,’z’:200}....}
Create a stack that stores dictionaries as elements.
Implement a `push_nested_dict` method to push a values of nested dictionary onto the stack.
- Implement a `pop_nested_dict` method to pop the top element from the stack.
for example : after implementing push_nested_dict() , the stack becomes: {‘y’:100,’z’:200}
{‘x’:10} {‘a’:’one,’b’:’two}
Ans
nested dictionary of the form:
nested_dict = {
1: {'a': 'one', 'b': 'two'},
2: {'x': 10},
3: {'y': 100, 'z': 200}
}
We want to:
Implement push_nested_dict(nested_dict) → to push each inner dictionary (value) onto
a stack.
Implement pop_nested_dict() → to pop and print the top dictionary from the stack
(LIFO).
# Create an empty stack
stack = []
# Push function
def push_nested_dict(nested_dict):
for value in nested_dict.values():
stack.append(value)
# Pop function
def pop_nested_dict():
if stack:
print("Popped:", stack.pop())
else:
print("Stack is empty.")
# Sample nested dictionary
nested_dict = {
1: {'a': 'one', 'b': 'two'},
2: {'x': 10},
3: {'y': 100, 'z': 200}
}
# Push all inner dictionaries
push_nested_dict(nested_dict)
# Show the stack (top to bottom)
print("Stack now:")
for item in reversed(stack):
print(item)
# Pop all items
pop_nested_dict()
pop_nested_dict()
pop_nested_dict()
pop_nested_dict() # Extra pop to show empty message
Output:
Stack now:
{'y': 100, 'z': 200}
{'x': 10}
{'a': 'one', 'b': 'two'}
Popped: {'y': 100, 'z': 200}
Popped: {'x': 10}
Popped: {'a': 'one', 'b': 'two'}
Stack is empty.
Q Write the definition of a function POP_PUSH (LPop, LPush, N) in Python.
The function should Pop out the last N elements of the list LPop and Push them into the list
LPush.
For example: If the contents of the list LPop are [10, 15, 20, 30] And value of N passed is 2,
then the function should create the list LPush as [30, 20] And the list LPop should now contain
[10, 15] NOTE: If the value of N is more than the number of elements present in LPop, then
display the message "Pop not possible".
Ans
def POP_PUSH(LPop, LPush, N):
if N > len(LPop):
print("Pop not possible")
else:
for _ in range(N):
item = LPop.pop() # Pop from LPop
LPush.append(item) # Push into LPush
LPop = [10, 15, 20, 30]
LPush = []
N=2
POP_PUSH(LPop, LPush, N)
print("LPop after operation:", LPop)
print("LPush after operation:", LPush)
Output:
LPop after operation: [10, 15]
LPush after operation: [30, 20]
Q A list contains following record of customer: [Customer_name, Room Type]
Write the following user defined functions to perform given operations on the stack named
'Hotel':
(i) Push Cust() - To Push customers' names of those customers who are staying in
'Delux' Room Type.
(ii) (ii) Pop Cust() - To Pop the names of customers from the stack and display them.
(iii) Also, display "Underflow" when there are no customers in the stack.
For example: If the lists with customer details are as follows:
[["Siddarth", "Delux"] ["Rahul", "Standard"] ["Jerry", "Delux"]]
The stack should contain Jerry Siddharth
The output should be: Jerry
Siddharth
Underflow
Ans
# Stack to hold customer names
Hotel = []
# List of customer records
customers = [
["Siddarth", "Delux"],
["Rahul", "Standard"],
["Jerry", "Delux"]
]
# Function to push 'Delux' room customers onto the stack
def PushCust():
for record in customers:
if record[1] == "Delux":
Hotel.append(record[0])
# Function to pop and display customer names from the stack
def PopCust():
while Hotel:
print(Hotel.pop())
print("Underflow")
# Call the functions
PushCust()
PopCust()
Output:
Jerry
Siddarth
Underflow
Q Write a function in Python,
Push (Vehicle) where, Vehicle is a dictionary containing details of vehicles
(Car_Name: Maker).
The function should push the name of car manufactured by TATA' (including all the possible
cases like Tata, TaTa, etc.) to the stack.
For example: If the dictionary contains the following data:
Vehicle=("Santro": "Hyundai", "Nexon": "TATA", "Safari": "Tata"}
The stack should contain Safari Nexon
Ans
# Stack to store car names made by TATA
stack = []
# Function to push TATA cars into the stack
def Push(Vehicle):
for car, maker in Vehicle.items():
if maker.lower() == "tata":
stack.append(car)
# Example dictionary
Vehicle = {"Santro": "Hyundai", "Nexon": "TATA", "Safari": "Tata"}
# Call the function
Push(Vehicle)
# Print the stack (from top to bottom)
print("Stack contents (top to bottom):")
for car in reversed(stack):
print(car)
Output:
Stack contents (top to bottom):
Safari
Nexon