LambdaLabTM
Computer Science · Class 12 · Data Structures
stackpractice⏱️ 22 min read

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.

The lesson these programs practiseWriting the Stack Functions — the lesson these programs lean on

1The shape, and why the output comes out backwards

function 1 · push what passes
for item in data:
    if the test:
        stack.append(item)
function 2 · pop them all
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.

🔍 Push what passes, then pop them all
the test: len(str(n)) >= 5
Nums
213
10025
167
254923
14
1297653
31498
386
92765
BigNums
empty
top is the highlighted item
screen

Nothing has run yet. First PushBig() goes through Nums, one item at a time.

The expected output is reversed on purpose
Items are pushed in the order they sit in the data, so the last one to pass is on top — and pop takes the top first. That is why every one of these questions prints its answer in the reverse of the data's order. If your output is in the original order, you have printed the list, not popped the stack.

21 · Push the numbers with five or more digits

📋 The problem

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)

big_nums.py
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()
Output
BigNums: [10025, 254923, 1297653, 31498, 92765]
92765
31498
1297653
254923
10025
Stack Empty
len(str(n)) >= 5

str(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

📋 The problem

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)

hotel.py
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()
Output
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.

A spelling slip in the paper
The question lists the customer as Siddarth and then shows the expected output as Siddharth. A program prints the name as it is stored, so the run above says Siddarth. Examiners mark the logic, not a typing slip in their own example.

43 · Push name and phone of customers in Goa

📋 The problem

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)

goa_customers.py
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()
Output
['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.

Note
The paper's data gives Gurdas eleven 9s, and its expected output shows ten. As with the Delux question, the program prints what is stored.

54 · Two conditions: outside India and under 3500 km

📋 The problem

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)

travel.py
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()
Output
['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

📋 The problem

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:

product.py
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)
Output
[('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)]
('Headphones', 1500)
('Mobile', 30000)
('Laptop', 90000)
Stack Empty
if 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.

One character different
The published answer prints "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

📋 The problem

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)

push_nv.py
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')
Output
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 = False

Reset 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

📋 The problem

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.py
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])
Output
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.

push_filter_try.py

10What to remember from all seven

Read the question for the test

Everything else is the same two functions. Find the one condition, and what exactly gets pushed.

Push what the question asks for

The whole record, one field of it, or a new list built from two fields — the question decides, not the data.

Brackets follow the question

Push_element() uses the named global list; Push_element(NList) takes the list as a parameter.

The message goes after the loop

Stack Empty, Underflow or EmptyStack is printed once, when the loop has emptied the stack.

The output is reversed

The last item pushed is on top, so it is printed first.

✍️ Now write these yourself
  1. 1

    Write Push3_5(N) to push every integer in N that is divisible by 3 or by 5 onto Only3_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. 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, push s[0].

  3. 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. 4

    Push every word from a sentence that starts with a capital letter.

    Hint · sentence.split(), then test word[0].isupper().

Quick Check

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?

Quick Check

Where should print('Stack Empty') go in a pop-all function?

Quick Check

A question says: push the product name and price of products costing more than 50. What is pushed for ('Pen', 50)?

Quick Check

while product: ... else: print('Stack Empty') — when does the else run?