Push What Passes a Test
Look at the 3-mark stack question in the last few board papers and you find the same two functions again and again. The first goes through some data and pushes every item that passes a test. The second pops everything off, printing each item, and then prints a message. Only the test changes. Learn the shape once, and each new question is mostly about writing one condition.
1The shape, and why the output comes out backwards
for item in data:
if the test:
stack.append(item)while len(stack) > 0:
print(stack.pop())
print('Stack Empty')Step through four real questions below. Watch the order the items go onto the stack, and then the order they reach the screen.
len(str(n)) >= 5Nothing has run yet. First PushBig() goes through Nums, one item at a time.
21 · Push the numbers with five or more digits
A list Nums contains random integers. Write PushBig() to push every number with 5 or more digits onto a stack BigNums, and PopBig() to pop and display them, then display “Stack Empty” when there are none left.(CBSE 2024 board paper · 3 marks)
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
BigNums = []
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:', BigNums)
PopBig()BigNums: [10025, 254923, 1297653, 31498, 92765] 92765 31498 1297653 254923 10025 Stack Empty
len(str(n)) >= 5str(n) turns 254923 into the text '254923', and len() counts its characters — which are its digits. For numbers that are not negative, n >= 10000 gives the same answer.
def PushBig():Empty brackets, because the question names the list and the stack. Both are made at the top of the program, and append() changes BigNums without needing global.
while len(BigNums) > 0:Pop while there is something to pop. When the stack is empty, the condition is False and the loop stops before an IndexError could happen.
print('Stack Empty')After the loop, not inside it — so it prints once, when the popping is over.
32 · Push the customers staying in Delux rooms
Each record is [Customer_name, Room_Type]. Write Push_Cust() to push the names of customers staying in ‘Delux’ rooms onto a stack Hotel, and Pop_Cust() to pop and display the names, then display “Underflow” when the stack is empty.(CBSE 2023 board paper · 3 marks)
customers = [['Siddarth', 'Delux'], ['Rahul', 'Standard'], ['Jerry', 'Delux']]
Hotel = []
def Push_Cust():
for c in customers:
if c[1] == 'Delux':
Hotel.append(c[0])
def Pop_Cust():
while len(Hotel) > 0:
print(Hotel.pop())
print('Underflow')
Push_Cust()
Pop_Cust()Jerry Siddarth Underflow
The test reads c[1], the room type, but the push stores c[0], the name. Pushing c itself would put the whole record on the stack, and the output would show both values with their brackets.
43 · Push name and phone of customers in Goa
Each record is [Customer_name, Phone_number, City]. Write Push_element() to push an object holding the name and phone number of customers who live in Goa onto a stack status, and Pop_element() to pop and display them, then display “Stack Empty”.(CBSE sample paper 2022-23 · 3 marks)
customers = [['Gurdas', '99999999999', 'Goa'],
['Julee', '8888888888', 'Mumbai'],
['Murugan', '77777777777', 'Cochin'],
['Ashmit', '1010101010', 'Goa']]
status = []
def Push_element():
for c in customers:
if c[2] == 'Goa':
status.append([c[0], c[1]])
def Pop_element():
while len(status) > 0:
print(status.pop())
print('Stack Empty')
Push_element()
Pop_element()['Ashmit', '1010101010'] ['Gurdas', '99999999999'] Stack Empty
status.append([c[0], c[1]])The question wants an object holding two things, not the whole record — so a new two-item list is built from the name and the phone, and that list is pushed.
'99999999999'Phone numbers are kept as strings, as the paper gives them. They are labels, not quantities, and nobody adds two phone numbers.
54 · Two conditions: outside India and under 3500 km
A nested list NList holds [City, Country, distance from Delhi]. Write Push_element(NList) to push [city, country] for every city that is not in India and is less than 3500 km from Delhi onto a stack travel, and Pop_element() to pop and display them, then display “Stack Empty”.(CBSE sample paper 2023-24 · 3 marks)
NList = [['New York', 'U.S.A.', 11734],
['Naypyidaw', 'Myanmar', 3219],
['Dubai', 'UAE', 2194],
['London', 'England', 6693],
['Gangtok', 'India', 1580],
['Columbo', 'Sri Lanka', 3405]]
travel = []
def Push_element(NList):
for city in NList:
if city[1] != 'India' and city[2] < 3500:
travel.append([city[0], city[1]])
def Pop_element():
while len(travel) > 0:
print(travel.pop())
print('Stack Empty')
Push_element(NList)
Pop_element()['Columbo', 'Sri Lanka'] ['Dubai', 'UAE'] ['Naypyidaw', 'Myanmar'] Stack Empty
and needs both parts to be True. Gangtok is under 3500 km but is in India; London is outside India but too far. Neither is pushed. This time the list comes in as a parameter, because the question writes Push_element(NList).
65 · Products costing more than 50 — the sample paper's own answer
L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]. Write Push_element() to push the product name and price of products costing more than 50 onto a stack Product, and Pop_element() to pop and display them, then display “Stack Empty”.(CBSE sample paper 2025-26 · 3 marks)
This is the answer CBSE published with the paper, run as it stands:
L = [("Laptop", 90000), ("Mobile", 30000), ("Pen", 50), ("Headphones", 1500)]
product = []
def Push_element(L):
for i in L:
if i[1] > 50:
product.append(i)
print(product)
def Pop_element(product):
while product:
print(product.pop())
else:
print("Stack Empty")
Push_element(L)
Pop_element(product)[('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]
('Headphones', 1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Emptyif i[1] > 50:The Pen costs exactly 50, and 50 > 50 is False — so it is left out. More than 50 means > 50, not >= 50.
while product:A list with items in it counts as True, an empty one as False. So this means the same as while len(product) > 0.
else:An else on a loop runs when the loop ends without a break. This loop has no break, so the else always runs once at the end — exactly like a print() placed after the loop.
def Pop_element(product):The parameter has the same name as the global list, and the call passes that list in. Inside the function, product is simply that same list.
"Stack Emply" — a typing slip. The question asks for Stack Empty, and that is what the version above prints.76 · Words with no vowels, read from the user
Write PushNV(N), which pushes every string in the list N that has no vowels onto a list NoVowel. Then write a program that inputs 5 words into a list All, uses PushNV(), and pops and displays each word, displaying “EmptyStack” when the stack is empty.(CBSE 2022 board paper, Term 2 · 3 marks)
All = []
NoVowel = []
def PushNV(N):
for word in N:
has_vowel = False
for ch in word:
if ch in 'AEIOUaeiou':
has_vowel = True
if has_vowel == False:
NoVowel.append(word)
for i in range(5):
word = input('Enter a word: ')
All.append(word)
PushNV(All)
while len(NoVowel) > 0:
print(NoVowel.pop(), end=' ')
print('EmptyStack')Enter a word: DRY Enter a word: LIKE Enter a word: RHYTHM Enter a word: WORK Enter a word: GYM GYM RHYTHM DRY EmptyStack
has_vowel = FalseReset for every word, inside the outer loop. Set it once above the loop and the first word with a vowel would mark every word after it too.
if has_vowel == False:After the inner loop has looked at every letter. Only then do you know the word has no vowel at all.
end=' 'The expected output is on one line — GYM RHYTHM DRY EmptyStack — so each popped word ends with a space instead of a new line.
87 · Pushing from a dictionary
Vehicle is a dictionary of {Car_Name: Maker}. Write Push(Vehicle) to push the name of every car made by ‘TATA’, in any mix of capitals (Tata, TaTa and so on), onto a stack.(CBSE 2023 board paper, alternative to question 2 · 3 marks)
Vehicle = {'Santro': 'Hyundai', 'Nexon': 'TATA', 'Safari': 'Tata'}
stack = []
def Push(Vehicle):
for car in Vehicle:
if Vehicle[car].upper() == 'TATA':
stack.append(car)
Push(Vehicle)
for i in range(len(stack) - 1, -1, -1):
print(stack[i])Safari Nexon
A for loop over a dictionary gives its keys — the car names — and Vehicle[car] looks up the maker. .upper() turns Tata, TaTa and tata all into TATA before comparing, which is how one test covers every spelling. The question shows the stack top first, as Safari then Nexon, so the last loop prints it that way without popping.
9Run one yourself
Change the test on the marked line and run it again. Try n % 5 == 0, or n < 100.
10What to remember from all seven
Everything else is the same two functions. Find the one condition, and what exactly gets pushed.
The whole record, one field of it, or a new list built from two fields — the question decides, not the data.
Push_element() uses the named global list; Push_element(NList) takes the list as a parameter.
Stack Empty, Underflow or EmptyStack is printed once, when the loop has emptied the stack.
The last item pushed is on top, so it is printed first.
- 1
Write
Push3_5(N)to push every integer inNthat is divisible by 3 or by 5 ontoOnly3_5. For[10, 6, 14, 18, 30], pop and display them on one line followed by StackEmpty. (CBSE 2022 Term 2, alternative)Hint ·
n % 3 == 0 or n % 5 == 0. The output should be 30 18 6 10 StackEmpty. - 2
Push the names of students who scored more than 75 from a list of
[name, marks]records, then pop them all.Hint · Test
s[1] > 75, pushs[0]. - 3
From a dictionary
{event: people}, push the events with more than 200 people, and print how many were pushed.Hint · Loop the keys, look up the value, and print
len(stack)after pushing. - 4
Push every word from a sentence that starts with a capital letter.
Hint ·
sentence.split(), then testword[0].isupper().
Nums = [12, 45, 7, 30]. The push function pushes numbers greater than 10, and the pop function pops and prints them all. What is printed first?
Where should print('Stack Empty') go in a pop-all function?
A question says: push the product name and price of products costing more than 50. What is pushed for ('Pen', 50)?
while product: ... else: print('Stack Empty') — when does the else run?