9 questions from CBSE board, sample and compartment papers (2024–2027), 3 marks, each with a model answer. Questions on implementing a stack with a Python list: push and pop functions, checking for an empty stack, and programs that push selected values or records and then pop and display them. Programming answers open in the Python Lab.
Data Structures (Stack)· 3 Marks· Q30· 2024 Board Paper Python
Consider a list named Nums which contains random integers.
Write the following user defined functions in Python and perform the specified operations on a stack named BigNums.
(i) PushBig() : It checks every number from the list Nums and pushes all such numbers which have 5 or more digits into the stack, BigNums.
(ii) PopBig() : It pops the numbers from the stack, BigNums and displays them. The function should also display "Stack Empty" when there are no more numbers left in the stack.
For example: If the list Nums contains the following data:
Nums = [213,10025,167,254923,14,1297653,31498,386,92765]
Then on execution of PushBig(), the stack BigNums should store:
[10025, 254923, 1297653, 31498, 92765]
And on execution of PopBig(), the following output should be displayed:
92765
31498
1297653
254923
10025
Stack Empty
Model answer
BigNums = []
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
def PushBig():
for n in Nums:
if len(str(n)) >= 5:
BigNums.append(n)
def PopBig():
while len(BigNums) > 0:
print(BigNums.pop())
print("Stack Empty")
BigNums = []
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
def PushBig():
for n in Nums:
if len(str(n)) >= 5:
BigNums.append(n)
def PopBig():
while len(BigNums) > 0:
print(BigNums.pop())
print("Stack Empty")
PushBig()
print("BigNums stack:", BigNums)
PopBig()
Data Structures (Stack)· 3 Marks· Q30· 2025 Board Paper Python
(a) A stack, named ClrStack, contains records of some colors. Each record is represented as a tuple containing four elements - ColorName, RED, GREEN, BLUE. ColorName is a string, and RED, GREEN, BLUE are integers. For example, a record in the stack may be ('Yellow', 237, 250, 68)
Write the following user-defined functions in Python to perform the specified operations on ClrStack:
(i) push_Clr(ClrStack, new_Clr): This function takes the stack ClrStack and a new record new_Clr as arguments and pushes this new record onto the stack.
(ii) pop_Clr(ClrStack): This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display the message "Underflow".
(iii) isEmpty(ClrStack): This function checks whether the stack is empty. If the stack is empty, the function should return True, otherwise the function should return False.
Data Structures (Stack)· 3 Marks· Q30· 2025 Board Paper Python
(b) Write the following user-defined functions in Python:
(i) push_trail(N,myStack): Here N and mystack are lists, and myStack represents a stack. The function should push the last 5 elements from the list N onto the stack myStack. For example, if the list N is [1,2,3,4,5,6,7], then the function push_trail() should push the elements 3,4,5,6,7 onto the stack. Therefore the value of stack will be [3,4,5,6,7].
Assume that N contains at least 5 elements.
(ii) pop_one(myStack): The function should pop an element from the stack myStack, and return this element. If the stack is empty, then the function should display the message 'Stack Underflow', and return None.
(iii) display_all(myStack): The function should display all the elements of the stack myStack, without deleting them. If the stack is empty, the function should display the message 'Empty Stack'.
def push_trail(N, myStack):
# Push last 5 elements of list N into stack myStack
for item in N[-5:]:
myStack.append(item)
def pop_one(myStack):
# Pop one element from stack
if len(myStack) == 0:
print('Stack Underflow')
return None
return myStack.pop()
def display_all(myStack):
# Display all elements of stack without deleting
if len(myStack) == 0:
print('Empty Stack')
else:
for item in myStack:
print(item, end=' ')
# Test Data
N = [1, 2, 3, 4, 5, 6, 7]
myStack = []
push_trail(N, myStack)
print(myStack)
print(pop_one(myStack))
display_all(myStack)
Data Structures (Stack)· 3 Marks· Q30· 2026 Board Paper Python
(a) A stack named FruitStack contains records represented as dictionaries. Write push_fruit(FruitStack, Fruit) to push if Price < 100, pop_fruit(FruitStack), and display(FruitStack). OR (b) Write a program to accept 10 integers, push 3-digit even integers to a stack, and pop/display them at the end.
# Solution for Option (A)
def push_fruit(FruitStack, Fruit):
if Fruit['Price'] < 100:
FruitStack.append(Fruit)
def pop_fruit(FruitStack):
if not FruitStack:
print("UNDERFLOW")
else:
return FruitStack.pop()
def display(FruitStack):
if not FruitStack:
print("EMPTY STACK")
else:
for f in reversed(FruitStack):
print(f)
# Test A
stack = []
push_fruit(stack, {'Name':'Apple', 'Price': 120}) # Won't push
push_fruit(stack, {'Name':'Banana', 'Price': 60}) # Will push
display(stack)
# Solution for Option (B)
# Mocking input for runner: [12, 31, 320, 457, 6, 92, 924, 220, 1, 218]
mock_inputs = [12, 31, 320, 457, 6, 92, 924, 220, 1, 218]
num_stack = []
for num in mock_inputs:
if 100 <= num <= 999 and num % 2 == 0:
num_stack.append(num)
print("\nPopping (Option B):")
while num_stack:
print(num_stack.pop(), end=' ')
Data Structures (Stack)· 3 Marks· Q30· 2025 Compartment Paper Python
(a) A stack named KeyStack contains records [Make, Keys, Connectivity]. Write functions push_key(KeyStack, new_key), pop_key(KeyStack), isEmpty(KeyStack). OR (b) Write functions push_vowels(S, St), pop_one(St), display_all(St).
# Solution for Part A
def push_key(KeyStack, new_key):
KeyStack.append(new_key)
def pop_key(KeyStack):
if not KeyStack:
print("Underflow")
else:
return KeyStack.pop()
def isEmpty(KeyStack):
return len(KeyStack) == 0
# Testing Part A
stack = []
push_key(stack, ['Hitech', 105, 'USB'])
print("Stack after push:", stack)
print("Popped item:", pop_key(stack))
pop_key(stack) # Should print Underflow
Data Structures (Stack)· 3 Marks· Q30· 2024 Sample Paper Python
A list, NList contains following record as list elements:
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user defined functions in Python to perform the specified operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object containing name of the city and country, which are not in India and distance is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the function should display “Stack Empty” when there are no elements in the stack.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
Model answer
travel = []
def Push_element(NList):
for L in NList:
if L[1] != "India" and L[2]<3500:
travel.append([L[0],L[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print("Stack Empty")
travel = []
def Push_element(NList):
for L in NList:
if L[1] != "India" and L[2]<3500:
travel.append([L[0],L[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print("Stack Empty")
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
Push_element(NList)
Pop_element()
Data Structures (Stack)· 3 Marks· Q30· 2025 Sample Paper
A) You have a stack named BooksStack that contains records of books. Each book record is represented as a list containing book_title, author_name, and publication_year. Write the following user-defined functions in Python to perform the specified operations on the stack BooksStack:
(I) push_book(BooksStack, new_book): This function takes the stack BooksStack and a new book record new_book as arguments and pushes the new book record onto the stack.
(II) pop_book(BooksStack): This function pops the topmost book record from the stack and returns it. If the stack is already empty, the function should display "Underflow".
(III) peep(BookStack): This function displays the topmost element of the stack without deleting it. If the stack is empty, the function should display 'None'.
OR
(B) Write the definition of a user-defined function `push_even(N)` which accepts a list of integers in a parameter `N` and pushes all those integers which are even from the list `N` into a Stack named `EvenNumbers`. Write function pop_even() to pop the topmost number from the stack and returns it. If the stack is already empty, the function should display "Empty". Write function Disp_even() to display all element of the stack without deleting them. If the stack is empty, the function should display 'None'. For example: If the integers input into the list `VALUES` are: [10, 5, 8, 3, 12] Then the stack `EvenNumbers` should store: [10, 8, 12]
# (A)
def push_book(BooksStack, new_book):
BooksStack.append(new_book)
def pop_book(BooksStack):
if BooksStack == []:
print("Underflow")
else:
return BooksStack.pop()
def peep(BooksStack):
if BooksStack == []:
print("None")
else:
print(BooksStack[-1])
# OR (B)
EvenNumbers = []
def push_even(N):
for x in N:
if x % 2 == 0:
EvenNumbers.append(x)
def pop_even():
if EvenNumbers == []:
print("Empty")
else:
return EvenNumbers.pop()
def Disp_even():
if EvenNumbers == []:
print("None")
else:
for x in EvenNumbers[::-1]:
print(x)
Data Structures (Stack)· 3 Marks· Q30· 2026 Sample Paper Python
A list containing records of products as
L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]
Write the following user-defined functions to perform operations on a stack named Product to:
I. Push_element() - To push an item containing the product name and price of products costing more than 50 into the stack.
Output: [('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]
II. Pop_element() - To pop the items from the stack and display them. Also, display "Stack Empty" when there are no elements in the stack.
Output:
('Headphones', 1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Empty
product = []
def Push_element(L):
for i in L:
if i[1] > 50:
product.append(i)
print("Stack after push:", product)
def Pop_element():
if not product:
print("Stack Empty")
else:
while product:
print(product.pop())
print("Stack Empty")
L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]
Push_element(L)
Pop_element()
Data Structures (Stack)· 3 Marks· Q30· 2027 Sample Paper Python
A list containing records of books is given as:
B = [("Machine Learning Basics", 550), ("World Geography", 450), ("Wonder World", 140), ("AI Revolution", 750)]
Write the following user-defined functions to perform operations on a stack named Books:
I. Push_element(): Push only those books whose price is more than 250 into the stack.
II. Pop_element(): Pop the items from the stack and display them.
After all items are popped, display "Stack Empty".
Expected Output:
('AI Revolution', 750)
('World Geography', 450)
('Machine Learning Basics', 550)
Stack Empty
Model answer
I.
B = [("Machine Learning Basics", 550),("World Geography", 450),("Wonder World", 140),("AI Revolution", 750)]
Books = [ ]
def Push_element():
for item in B:
if item[1] > 250:
Books.append(item)
II.
def Pop_element():
while Books:
print(Books.pop())
print("Stack Empty")
B = [("Machine Learning Basics", 550),("World Geography", 450),("Wonder World", 140),("AI Revolution", 750)]
Books = [ ]
def Push_element():
for item in B:
if item[1] > 250:
Books.append(item)
def Pop_element():
while Books:
print(Books.pop())
print("Stack Empty")
Push_element()
Pop_element()