Skip to content
Computer ScienceCBSE Class 12 · Stack

Stack Programs for the Board: Conditional Push and Pop All (Class 12 Computer Science)

Updated 17 October 2026 · Fact-checked

A board stack program has two or three functions: one scans a list or dictionary and pushes only the items that meet a condition onto a stack, and another pops and prints every item until the stack is empty, printing "Stack Empty" at the end. Use append() to push and pop() to pop, with the stack passed as a parameter.

Only items passing the condition are pushed, and pop() returns the last one first, so the output is in reverse order before Stack Empty.

Illustration drawn for QuestionBuddy.

Understand Stack Programs: Conditional Push and Pop All

The 3-mark stack question in the CBSE paper has a fixed shape. A small collection (a list of numbers, a list of names, or a dictionary of names and marks) is given. You write a function that pushes only the items that satisfy a condition and a function that pops everything and shows it.

Part 1: conditional push.

def push_big(stack, data):
    for x in data:
        if x > 50:
            stack.append(x)

Loop over the data, test the condition, and append to the stack. Nothing is returned because the list changes in place.

Part 2: pop all.

def pop_all(stack):
    if stack == []:
        print("Stack Empty")
    else:
        while stack != []:
            print(stack.pop())

Because items leave from the top, the output is in the reverse of the push order.

Stacks of dictionary data. If the data is a dictionary such as {"Asha": 88, "Ravi": 64}, iterate with .items() or .keys(). To push a name when the mark meets a condition: for name in d: if d[name] > 75: stack.append(name). Pushing a pair as a list or tuple, stack.append((name, d[name])), is also accepted; make clear what each stack item is.

Records. A stack of records stores each item as a list like [roll, name]. Pop returns the whole record, and you index it to print a field.

Answer format that scores. Write the function headers exactly as the question names them, keep the indentation correct, and do not use print inside the push function unless asked. Where a driver program is asked for, create the empty list once, call the push function with the data and the pop function once.

Stack Programs: Conditional Push and Pop All: key facts

Conditional push
  • for x in data:
  • if condition:
  • stack.append(x)
Push order follows the order of the data.
Pop all
  • while stack != []:
  • print(stack.pop())
  • After the loop the stack is empty
Print Stack Empty when it is empty at the start.
Dictionary data
  • for k in d: use d[k] for the value
  • or for k, v in d.items()
  • append k, v or (k, v) as the question asks
State what each stack item is.
Output order
Pop order is the reverse of push order | The last pushed item prints first
Check by writing the stack after the pushes.

How to answer Stack Programs: Conditional Push and Pop All questions

Follow this order for any 3-mark conditional stack question.

  1. 1Read what goes on the stack: the whole item, only the key, or a pair.
  2. 2Write the condition from the question word by word (greater than, even, starts with a vowel, and so on).
  3. 3Write push as a loop with an if and append; do not return anything.
  4. 4Write pop-all as a while loop that pops until the list is empty; add the Stack Empty message for the starting-empty case.
  5. 5Trace with the sample data: list the pushed items in order, then reverse them to get the output.
  6. 6State the output clearly, line by line, after the code.

Stack Programs: Conditional Push and Pop All in real life

The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

Low-stock alerts

Suppose a shop holds item quantities in a list qty = [12, 3, 45, 2, 30]. Items with quantity below 5 are pushed on a stack for restocking, then displayed.

Which quantities are pushed, and in what order are they displayed?

Try it first, then show the solutionSolution
  1. Scan in order: 12 no, 3 yes, 45 no, 2 yes, 30 no. The stack is [3, 2].
  2. Pop all prints the top first.

Answer: Output: 2 then 3

Memory hook: The newest alert is shown first.

Top scorers

Suppose a class dictionary is marks = {"Asha": 88, "Ravi": 64, "Joy": 91}. Names with marks above 80 are pushed and then popped.

Show the output.

Try it first, then show the solutionSolution
  1. Asha (88) is pushed, Ravi (64) is not, Joy (91) is pushed: [Asha, Joy].
  2. Popping prints Joy then Asha.

Answer: Joy then Asha

Memory hook: The last pushed name leaves first.

Tricks to remember Stack Programs: Conditional Push and Pop All

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • Filter, then flip

    Push only passers; the output is the passers in reverse.

    Use it when: Predicting the output order.

  • One loop to push, one loop to pop

    Each function has a single loop and one job.

    Use it when: Structuring the 3-mark answer.

  • While not empty

    while stack != []: keeps popping until nothing remains.

    Use it when: Pop-all loop.

  • Dictionary: keys for names, values for tests

    d[k] is the mark when k is the name.

    Use it when: Dictionary stack questions.

Stack Programs: Conditional Push and Pop All: solved examples

Ordered from board level to HOTS. Try each one before you open the solution.

Example 1: Output order of a conditional push · 1 mark · Very short answerBoard level

For st = [] and data = [5, 70, 12, 66, 90], push_big(st, data) pushes numbers greater than 50. What does pop_all(st) print?

Try it first, then show the solutionSolution
  1. Numbers above 50 in order: 70, 66, 90, so st = [70, 66, 90].
  2. pop prints from the top: 90, 66, 70.

Answer: 90
66
70

Example 2: Push even numbers · 3 marks · Short answerHarder board level

Write a function push_even(stack, data) that pushes only the even numbers of the list data onto the stack, and a function pop_all(stack) that prints and removes every item, printing Stack Empty if the stack is empty at the start. Show the output for data = [3, 8, 5, 6, 2].

Try it first, then show the solutionSolution
  1. def push_even(stack, data):
        for x in data:
            if x % 2 == 0:
                stack.append(x)
    
    def pop_all(stack):
        if stack == []:
            print("Stack Empty")
        else:
            while stack != []:
                print(stack.pop())
    (2 marks)
  2. Evens in order: 8, 6, 2; the stack is [8, 6, 2]; the output is 2, 6, 8 on separate lines. (1 mark)

Answer: 2
6
8

Example 3: Stack from a dictionary · 3 marks · Short answerHarder board level

A dictionary is d = {"Asha": 88, "Ravi": 64, "Meena": 79, "Joy": 91}. Write push_names(stack, d) to push the names of students scoring 80 or more, and show the output of the pop loop.

Try it first, then show the solutionSolution
  1. def push_names(stack, d):
        for name in d:
            if d[name] >= 80:
                stack.append(name)
    (2 marks)
  2. Asha (88) and Joy (91) qualify; stack = ['Asha', 'Joy']. Popping prints Joy, then Asha. (1 mark)

Answer: Joy
Asha

Example 4: Stack of pairs · 3 marks · Short answerHarder board level

The list recs = [[1, "Asha"], [2, "Ravi"], [3, "Meena"]] holds roll number and name. Write code that pushes the records with an odd roll number onto stack st and then pops and prints only the names.

Try it first, then show the solutionSolution
  1. st = []
    for r in recs:
        if r[0] % 2 == 1:
            st.append(r)
    while st != []:
        print(st.pop()[1])
    (2 marks)
  2. Rolls 1 and 3 are pushed: [[1,"Asha"],[3,"Meena"]]. The pops print Meena then Asha. (1 mark)

Answer: Meena
Asha

Example 5: Case: library returns · 4 marks · Case-basedHOTS / competency

Suppose a library keeps the titles of returned books in the list books = ["Wings", "Gitanjali", "Godaan", "Malgudi", "Kamayani"]. Books whose title has more than 6 letters go to the shelving stack, and the shelver takes books from the top.
(i) Write push_long(stack, books). (1 mark)
(ii) Write the order in which the shelver gets the books. (2 marks)
(iii) A student asks whether the order would change if the list were scanned from the end. Answer with reason. (1 mark)

Try it first, then show the solutionSolution
  1. (i)
    def push_long(stack, books):
        for t in books:
            if len(t) > 6:
                stack.append(t)
  2. (ii) Lengths: Wings 5, Gitanjali 9, Godaan 6, Malgudi 7, Kamayani 8. Pushed: Gitanjali, Malgudi, Kamayani. The shelver pops Kamayani, Malgudi, Gitanjali.
  3. (iii) Yes. Scanning from the end pushes Kamayani first, so the stack and the pop order reverse: Gitanjali, Malgudi, Kamayani.

Answer: (ii) Kamayani, Malgudi, Gitanjali

Where students lose marks in Stack Programs: Conditional Push and Pop All

The slips examiners see most often, and what to write instead.

  • Mistake: Printing in the push function instead of pushing

    The stack stays empty, so nothing can be popped later.

    Wrong working

    for x in data:
    if x > 50:
    print(x)

    Right working

    for x in data:
    if x > 50:
    stack.append(x)

    Do this: Use append in the push function; print only in the pop function.

    Usually costs: 1 to 1.5 marks

  • Mistake: Wrong output order

    Pop gives the last pushed first; many students write the push order.

    Wrong working

    Pushed 70, 66, 90 and printed 70, 66, 90

    Right working

    Printed 90, 66, 70

    Do this: Write the stack, then read it from the top.

    Usually costs: 1 mark

  • Mistake: Looping with for over the stack while popping

    Changing a list while iterating over it skips items.

    Wrong working

    for x in stack:
    print(stack.pop())

    Right working

    while stack != []:
    print(stack.pop())

    Do this: Use a while loop to empty a stack.

    Usually costs: 1 mark

  • Mistake: Missing the empty message

    The question may say print Stack Empty when no item remains; without the test it silently prints nothing.

    Wrong working

    while stack != []: print(stack.pop())

    Right working

    if stack == []: print("Stack Empty") with else: loop

    Do this: Add the test if the question mentions it.

    Usually costs: 0.5 mark

Exam tips

  • Write the function names exactly as given in the question; the marking scheme checks them.
  • Do not use global for the stack: pass it as a parameter, or note that append works on the global list without it.
  • Always append the thing the question says (key, pair or whole record).
  • After the code, add one dry run with the sample data and list the output lines.
  • If the question says "display the stack from top", use the reverse loop instead of popping.

Practice questions on Stack Programs: Conditional Push and Pop All

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · Very short answerBoard level

    In a stack program, the items are printed by popping until the stack is empty. In what order do they appear compared with the order they were pushed?

    Hint

    Think LIFO.

    Answer

    In the reverse order.

  2. Q2 · 1 mark · Very short answerBoard level

    Write a statement that pushes the value x onto a stack st only if x is divisible by 5.

    Hint

    One if and one append.

    Answer

    if x % 5 == 0: st.append(x)

  3. Q3 · 3 marks · Short answerHarder board level

    Write push_odd(stack, data) to push the odd numbers in data and show the pop-all output for data = [4, 7, 9, 10, 3].

    Hint

    Odd means remainder 1 when divided by 2.

    Answer
    def push_odd(stack, data):
        for x in data:
            if x % 2 == 1:
                stack.append(x)

    Odds in order: 7, 9, 3. Popping prints 3, 9, 7.

  4. Q4 · 3 marks · Short answerHarder board level

    A dictionary price = {"pen": 10, "book": 120, "bag": 450, "ink": 60} is given. Write code to push the names of items costing more than 50 into a stack s and then pop and print them, and state the output.

    Hint

    Dictionary order follows insertion.

    Answer
    s = []
    for item in price:
        if price[item] > 50:
            s.append(item)
    while s != []:
        print(s.pop())

    Pushed: book, bag, ink. Output: ink, bag, book.

  5. Q5 · 3 marks · Short answerHOTS / competency

    A stack st = [3, 8] is used with this code. What is the output?

    st = [3, 8]
    while len(st) < 5:
        if st[-1] % 2 == 0:
            st.append(st[-1] // 2)
        else:
            st.append(st[-1] * 3 + 1)
    print(st)
    Hint

    Check the top each time; stop when len is 5.

    Answer

    Top 8 is even: append 4 gives [3, 8, 4]. Top 4 is even: append 2 gives [3, 8, 4, 2]. Top 2 is even: append 1 gives [3, 8, 4, 2, 1]. len is 5 so stop. Output: [3, 8, 4, 2, 1].

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.In what order do popped items appear compared with the pushed order?Show answer

    Reverse.

  2. 2.Which loop empties a stack safely?Show answer

    while stack != []: with pop inside.

  3. 3.How is a dictionary value read when the key is name?Show answer

    d[name].

  4. 4.What does stack.append((k, v)) push?Show answer

    A pair (tuple) of key and value as one item.

  5. 5.Which function should print, push or pop-all?Show answer

    Pop-all; the push function should only append.

  6. 6.What should pop-all show if the stack starts empty?Show answer

    Stack Empty (or the message the question names).

Stack Programs: Conditional Push and Pop All: frequently asked questions

How do I push only some elements onto a stack in Python?

Loop over the data, test the condition with an if, and call append on the stack list inside the if. Items that fail the test are skipped.

Why does my stack output come out reversed?

That is correct: a stack is LIFO, so the last pushed item is popped first. The output order is the reverse of the order in which items were pushed.

Can a stack hold dictionary or list data in the board question?

Yes. The question tells you what to push: names, marks, or a record such as a list or tuple. Push exactly that.

Do I need a global statement for the stack list?

No, if you pass the list as a parameter or only use append and pop on it. A global statement is needed only if the function assigns a new list to the name.