CBSE Class 12 · Computer Science 083 · Data structure: stack 2026-27

Stack class 12 computer science: push, pop, and the three-mark question.

A stack has one open end. Whatever went in last comes out first, and that single rule is the whole chapter. The paper turns it into a pair of functions: one that pushes some of the data you are given, and one that pops and displays it. Below, the rule is traced, the operations are written with a Python list, and the exam pair is built from a list, tuples, a dictionary and words, so that no form of the question is new to you.

Live one to one · six programs with real output · your push and pop checked against the question · evenings or weekends, you say

Start here

Keep going after the stack

For the board the stack is the only data structure. These three courses cover the paper around it and what comes next in Python and SQL.

Ans. The short version

A stack in class 12 computer science is a linear data structure that works last in, first out: items are added (push) and removed (pop) at one end only, called the top. CBSE 083 for 2026-27 asks for a stack implemented with a Python list, where append() pushes and pop() removes, and the program must check for an empty stack, called underflow. The official sample paper gives it a 3-mark question. Modern Age Coders teaches it live, personalised one to one, at your own days and timing, with a priority demo to try first.

Q1. What is a stack?

What is a stack in Class 12 Computer Science?

A stack is a collection in which the last item added is the first one removed, written LIFO: last in, first out. Think of suitcases pushed one after another into a narrow luggage van with a single door.

Seven moves, traced

OperationList after itTopComes out
push Jaipur['Jaipur']Jaipur
push Kota['Jaipur', 'Kota']Kota
pop['Jaipur']JaipurKota
push Bundi['Jaipur', 'Bundi']Bundi
push Ajmer['Jaipur', 'Bundi', 'Ajmer']Ajmer
pop['Jaipur', 'Bundi']BundiAjmer
peek['Jaipur', 'Bundi']Bundinothing, Bundi is only seen

Six words to use in answers

  • Push: add an item on the top.
  • Pop: remove the item on the top and give it back.
  • Peek: look at the top item and leave it there.
  • Top: the open end. In a list, the last index, or -1.
  • Underflow: trying to pop from an empty stack.
  • Overflow: trying to push on a stack that is already full.

How much of data structure is there in Class 12? Only this. The 083 line for 2026-27 reads stack, its operations push and pop, and implementation using a list. Queues, linked lists and trees are not in it, and neither is changing infix expressions to postfix. Peek and display are not named, but they are small and questions borrow the ideas.

Q2. How is it written?

Push and pop in Class 12: implementing a stack using a list

In Python a list becomes a stack the moment you agree to use only one end of it. append() is push and pop() with nothing in the brackets is pop, both at the right-hand end.

The four operationslibrary return pile
def push(pile, book):
    """Place book on the top of the pile."""
    pile.append(book)

def pop(pile):
    """Remove and return the top book."""
    if pile == []:
        return "Underflow"
    return pile.pop()

def peek(pile):
    """Return the top book without removing it."""
    if pile == []:
        return "Nothing to see"
    return pile[-1]

def display(pile):
    """Show the pile from the top downwards."""
    for i in range(len(pile) - 1, -1, -1):
        print("  ", pile[i])

returns = []
push(returns, "Malgudi Days")
push(returns, "Gitanjali")
push(returns, "Godan")
display(returns)
print("Pop:", pop(returns))
print("Peek:", peek(returns))
print("Pop:", pop(returns))
print("Pop:", pop(returns))
print("Pop:", pop(returns))

Output

   Godan
   Gitanjali
   Malgudi Days
Pop: Godan
Peek: Gitanjali
Pop: Gitanjali
Pop: Malgudi Days
Pop: Underflow
A stack with a limitoverflow
LIMIT = 3

def add_plate(tray, plate):
    """Push only if the tray has room."""
    if len(tray) == LIMIT:
        print("Overflow,", plate, "not added")
    else:
        tray.append(plate)

tray = []
for p in ["steel", "glass", "clay", "brass"]:
    add_plate(tray, p)
print(tray)

Output

Overflow, brass not added
['steel', 'glass', 'clay']

A Python list grows as you append, so overflow appears only when the question fixes a size.

Which end, which method?

Push withPop withIs it a stack?
append(x)pop()Yes, top at the end. Use this one
insert(0, x)pop(0)Yes, top at index 0. Correct but slower
append(x)pop(0)No. The first item in comes out first
append(x)remove(x)No. It can take from the middle

Without a check, pop() on an empty list raises IndexError with the message "pop from empty list". An exception block could catch it, as on exception handling for Class 12, but a simple if is what the stack chapter expects.

Q3. What does the board ask?

Stack in Python Class 12 programs: the push and pop pair

Expect some data and two functions: push the items that meet a condition, then pop and display until the stack is empty, with a message. In the official 2026-27 sample paper this is Question 30, for 3 marks, and the marking scheme gives one and a half to each function.

1. From a list of tuplespush one field
Parcels = [("P11", "Surat", 12), ("P12", "Kochi", 4),
           ("P13", "Patna", 18), ("P14", "Leh", 10)]
Heavy = []

def push_heavy():
    """Push the ID of parcels above 9 kg."""
    for rec in Parcels:
        if rec[2] > 9:
            Heavy.append(rec[0])

def pop_heavy():
    """Pop and display every ID, then a message."""
    while Heavy != []:
        print(Heavy.pop())
    print("Van is empty")

push_heavy()
pop_heavy()

Output

P14
P13
P11
Van is empty

Only rec[0] is pushed, because the question says the ID and not the whole record.

2. From a dictionarypush the keys
Shelf = {"Scale": 6, "Pen": 40, "Glue": 3, "Atlas": 9}

def Push(stock, names):
    """Push names of items with fewer than 10 left."""
    for item in stock:
        if stock[item] < 10:
            names.append(item)

def Pop(names):
    """Return the top name, or None if empty."""
    if len(names) == 0:
        return None
    return names.pop()

Low = []
Push(Shelf, Low)
print(Low)
print(Pop(Low), Pop(Low), Pop(Low), Pop(Low))

Output

['Scale', 'Glue', 'Atlas']
Atlas Glue Scale None

Looping over a dictionary gives keys. The quantity is stock[item].

3. From a list of numberspop and total
def push_sevens(numbers):
    """Return a stack of the multiples of 7."""
    stack = []
    for n in numbers:
        if n % 7 == 0:
            stack.append(n)
    return stack

def pop_total(stack):
    """Pop every number, display it, return the sum."""
    total = 0
    while len(stack) > 0:
        top = stack.pop()
        print(top, end=" ")
        total += top
    print()
    return total

S = push_sevens([21, 30, 49, 14, 8, 70])
print("Sum:", pop_total(S))
print("Left:", S)

Output

70 14 49 21 
Sum: 154
Left: []
4. From the words of a sentencepop only some
def push_words(line):
    """Push words that begin with a vowel."""
    stack = []
    for word in line.split():
        if word[0].lower() in "aeiou":
            stack.append(word)
    return stack

def pop_some(stack, n):
    """Pop n words, or report underflow."""
    for i in range(n):
        if stack:
            print("Popped", stack.pop())
        else:
            print("Underflow")
            break

W = push_words("Every evening our team eats an orange")
print(W)
pop_some(W, 2)
pop_some(W, 6)

Output

['Every', 'evening', 'our', 'eats', 'an', 'orange']
Popped orange
Popped an
Popped eats
Popped our
Popped evening
Popped Every
Underflow
5. From nested lists, with a choicecondition is a parameter
Entries = [["Ila", "Kabaddi", 17], ["Dev", "Chess", 15],
           ["Roop", "Kabaddi", 16], ["Tara", "Chess", 18]]
Team = []

def push_sport(sport):
    """Push [name, age] for the given sport."""
    for e in Entries:
        if e[1] == sport:
            Team.append([e[0], e[2]])

def show_top():
    """Display the top entry, if there is one."""
    if Team:
        print("Top:", Team[-1][0], "age", Team[-1][1])
    else:
        print("No entry")

show_top()
push_sport("Kabaddi")
show_top()
print(Team)

Output

No entry
Top: Roop age 16
[['Ila', 17], ['Roop', 16]]

Team[-1][0]: first the top entry, then the name inside it.

6. Reverse a stringwhat a stack is good for
def backwards(text):
    """Return text reversed, using a stack."""
    stack = []
    for ch in text:
        stack.append(ch)
    result = ""
    while stack:
        result += stack.pop()
    return result

print(backwards("Konark"))
word = "malayalam"
print(word == backwards(word))

Output

kranoK
True

Pushing then popping everything always reverses the order, so it also tests for a palindrome.

The suggested practical list for 083 includes a program to implement a stack using a list. A menu-driven version for the file is in the Class 12 practical file guide.

Q4. Where do the marks slip away?

How to write the 3-mark stack answer

Before you write a line, underline five things in the question: the name of the stack, what is pushed, the condition, how many items are popped, and the exact message at the end.

  1. Name

    If it says a stack named Books, write Books = [] once, outside both functions.

  2. Item

    Whole record, or one field of it? Append just what is asked.

  3. Condition

    "Above 9" is > 9. "9 or more" is >= 9. Check the value that sits on the border.

  4. Pop

    One item needs an if. All items need a while.

  5. Message

    Copy its spelling and capitals. After popping all, print it below the loop and not inside.

SlipResultRepair
Heavy = [] inside pushA local stack fills and is lost when the function endsCreate it outside, or return it
for x in stack: stack.pop()About half the items stay behindwhile stack:
stack.append[x]TypeError: a method needs round bracketsstack.append(x)
Message inside the while loopIt prints after every popUnindent it
print(stack[::-1]) for popLooks right, but nothing is removedCall pop()
Naming your function pop and forgetting the listYou return, but the stack is unchangedThe line stack.pop() must be inside

A global stack can be appended to without writing global, because the name is never assigned again. The reason is on functions and scope.

Q5. Ready to be tested?

Stack Class 12 important questions with answers

Seventeen original questions, from one mark to three. For the output ones, draw the stack as a column and cross out what is popped: it is slower for the first two and faster ever after.

One mark

  1. Which list method performs the push operation when the top is at the end?
    Answer append()
  2. S = [11, 22, 33], then S.pop(), then print(S.pop()). What is printed?
    Answer 22. The first pop removed 33.
  3. Which exception does Python raise for pop() on an empty list?
    Answer IndexError.
  4. A, B, C and D are pushed in that order. Two pops follow. What is on the top now?
    Answer B. D and C have gone.
  5. Trying to delete an item from a stack that has none is called ______.
    Answer underflow
  6. 1, 2 and 3 are pushed in this order, with pops allowed at any time in between. Which order of popping is impossible? (a) 3, 2, 1 (b) 2, 1, 3 (c) 3, 1, 2 (d) 1, 2, 3
    Answer (c) 3, 1, 2. If 3 comes out first, 2 lies above 1, so 2 must be next.
  7. True or False: the peek operation reduces the number of items by one.
    Answer False. Peek only reads the top.
  8. Assertion (A): Overflow is not usually seen in a stack made with a Python list. Reason (R): A list can grow when items are appended to it.
    Answer Both A and R are true, and R is the correct explanation of A.

Two marks, theory

  1. Differentiate between overflow and underflow.
    Answer Overflow is trying to push on a stack that is full; underflow is trying to pop from a stack that is empty. With a Python list, underflow is the one to check for, since no size is fixed.
  2. Write any two situations in which a stack is useful, with the reason.
    Answer Undo in an editor: the latest change must be reversed first. The back button of a browser: the page visited last is shown first. Both need last in, first out.

Two marks, correct the code

  1. The functions should push names longer than five letters and later pop and show them all. Remove the four errors.
    Q11four errors
    Stack = []
    def Push(names):
        for n in names
            if len(n) > 5:
                Stack.add(n)
    def Pop():
        while len(Stack) = 0:
            print(Stack.pop(0))
    Answer
    Q11 correctedhalf a mark each
    Stack = []
    def Push(names):
        for n in names:             # 1. colon
            if len(n) > 5:
                Stack.append(n)     # 2. append
    def Pop():
        while len(Stack) != 0:      # 3. != in place of =
            print(Stack.pop())      # 4. no index
    
    Push(["Bhavani", "Tapi", "Narmada"])
    Pop()

    Output

    Narmada
    Bhavani

For MCQs on every chapter, take the Class 12 CS MCQ test.

Two marks, output

  1. Predict the output.
    Q12predict
    s = []
    for ch in "KAVERI":
        if ch in "AEIOU":
            s.append(ch)
        elif s:
            print(s.pop(), end="-")
    print(s)
    Answer Output
    A-E-['I']
    K finds the stack empty and does nothing. V pops A, R pops E, and I is pushed last.
  2. Predict the output.
    Q13predict
    def move(p, q):
        while len(p) > 1:
            q.append(p.pop())
    
    x = [10, 20, 30, 40]
    y = []
    move(x, y)
    print(x, y)
    print(y.pop(), x.pop())
    Answer Output
    [10] [40, 30, 20]
    20 10
    Moving from one stack to another reverses the order. The loop stops with one item left.
  3. Predict the output.
    Q14predict
    s = []
    for n in [3, 6, 2, 9, 4]:
        while s and s[-1] > n:
            s.pop()
        s.append(n)
    print(s)
    Answer Output
    [2, 4]
    2 throws out 6 and 3. Then 9 is pushed, and 4 throws out 9.
  4. Predict the output.
    Q15predict
    s = [5, 8]
    s.append(s.pop() + s[-1])
    print(s)
    s.append(s.pop() * 2)
    print(s)
    Answer Output
    [5, 13]
    [5, 26]
    pop() removes 8 first, so s[-1] is 5 and 13 is pushed. Then 13 is popped, doubled and pushed.

Three marks, write both functions

  1. A list Temps holds night temperatures. Write push_cold(Temps) to push those below zero into a stack named Cold, and pop_cold() to pop them all, displaying each, and then display how many were popped.
    Answer
    Q16one good answer
    Cold = []
    
    def push_cold(Temps):
        for t in Temps:
            if t < 0:
                Cold.append(t)
    
    def pop_cold():
        count = 0
        while Cold:
            print(Cold.pop())
            count += 1
        print("Popped:", count)
    
    push_cold([4, -2, 0, -7, 1, -3])
    pop_cold()

    Output

    -3
    -7
    -2
    Popped: 3

    Zero is not below zero: the border value again.

  2. A dictionary Phones holds models and prices. Write push_phone() to push (model, price) as a tuple for prices under 15000 into a stack named Budget, and pop_phone() to remove and display only the top one, or display "Nothing left".
    Answer
    Q17one good answer
    Phones = {"Nova": 12500, "Zeta": 31000, "Pico": 9900}
    Budget = []
    
    def push_phone():
        for model in Phones:
            if Phones[model] < 15000:
                Budget.append((model, Phones[model]))
    
    def pop_phone():
        if Budget:
            print(Budget.pop())
        else:
            print("Nothing left")
    
    push_phone()
    pop_phone()
    pop_phone()
    pop_phone()

    Output

    ('Pico', 9900)
    ('Nova', 12500)
    Nothing left

One question, five shapes

In class the same condition is asked on a list, a tuple, a dictionary and nested lists, until the data no longer decides whether you can start.

Paper first, then Python

You write both functions by hand, the teacher types exactly what you wrote, and you watch what your own indentation does.

A clock, gently

Once the pair is secure, it is timed. Minutes saved here are spent on case questions and SQL.

When the stack feels easy, sit a full paper: Class 12 CS sample paper 2026-27 with solutions, then the mixed important questions.

Personalised, one to one

Three marks here are the easiest to make safe

The stack question changes its data and keeps its shape, so a student who has written the pair ten times, with someone checking each line, has little to fear. That checking is what one to one is for. You choose the days and the timing. Take a priority demo to see a full class at work; enrol afterwards and its fee is adjusted in the first month. A free demo class exists too. The fee is monthly, there is no admission charge, and any month can be your last.

Before you enrol · Try a class

Priority demo, at a slot you pick

a full live class of about 45 to 60 minutes

  • You write a push and pop pair for data you have not met
  • Your code is typed as written and run in front of you
  • The five-point reading of a stack question, practised once
  • A written skill report, including any list gap from Class 11
Book a priority demo

The classes · Choose your own timing

Personalised one to one

₹4,999

per month, 4 private classes, fully flexible timing

  • Push and pop from lists, tuples, dictionaries and words
  • Hand-written answers checked for indentation and messages
  • Your practical file stack program explained for the viva
  • Then files, SQL or networks, in the order you need them
Ask for a personalised plan

Most of the time the stack itself is quick, and the lesson moves to whatever was hiding behind it: looping over a dictionary, indexing a nested list, or a while loop that never ends. Tell us which of these sounds like you. Look for the monthly fee in your own currency on this page.

Studying outside India?

One to one for CBSE students overseas

A student in Abu Dhabi, Dammam, Lagos or Kuala Lumpur can be asked the same push and pop pair as a student in Delhi. Lessons are placed in your afternoon, evening or weekend morning.

Where you liveTime differenceUsual class window, local timeFormat
India
every Indian city
Indian timeAny time you choosePersonalised 1-on-1
UAE and Oman
Dubai, Abu Dhabi, Sharjah, Muscat
1 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Saudi Arabia, Qatar, Kuwait, Bahrain
Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama
2 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Nepal
Kathmandu
15 min ahead of India4:30 PM to 9:00 PMPersonalised 1-on-1
Ethiopia and East Africa
Addis Ababa and East Africa Time
2 h 30 min behind India4:30 PM to 9:00 PMPersonalised 1-on-1
Singapore and Malaysia
Singapore, Kuala Lumpur
2 h 30 min ahead of India3:30 PM to 9:00 PMPersonalised 1-on-1

Handwritten practice works online as well: hold the page to the camera or send a photo in the lesson, and it is marked with you watching. All you need is Python on the computer, paper and a pen.

What families say

Rated 4.9 across 547 Google reviews

Real reviews from real families. We neither write nor commission them.

★★★★★

"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."

Ria Mukherjee

Parent

★★★★★

"Modern Age Coders has been a game-changer for me. I struggled to grasp IT concepts and coding before joining, but their classes transformed everything. I can now confidently write complex programs with ease."

Samriddha Mondal

Student

★★★★★

"One of the most wonderful education centres out there. Education is not limited to school syllabus but focuses on skill development."

Vansh Agarwal

Student

★★★★★

"My child Dhairya is really enjoying the Modern Age Coders classes. This is his first online class and he eagerly looks forward to it. I can already see his improvement, and the teachers are very cooperative."

Sonam Oswal

Parent of Dhairya

★★★★★

"Modern Age Coders have wonderful teachers who teach in a clear, easy and practical way. The teacher boosts students' confidence and inspires them to learn without hesitation."

Sonu Goyal

Parent

★★★★★

"I highly recommend this computer coding class! The teachers are incredibly knowledgeable and passionate about coding."

Ritu Kedia

Parent

The rest of the Class 12 series

More pages for Class 12 students

Every page in the CBSE Class 12 Computer Science series, grouped by what you need.

Stack doubts

Stack in Class 12 Computer Science: doubts answered

What is a stack in Class 12 Computer Science?

A stack is a linear data structure in which items are added and removed at one end only, called the top. It follows LIFO, last in, first out. In CBSE 083 for 2026-27 you implement it with a Python list and write functions for the push and pop operations.

How many marks is the stack in Class 12 CS?

CBSE does not publish a separate weightage for it; the stack is part of Unit 1, which has 40 of the 70 theory marks. In the official 2026-27 sample paper, Question 30 is a stack question of 3 marks with one and a half marks for each of its two functions.

Is queue in the Class 12 Computer Science syllabus 2026-27?

No. The only data structure in the Class 12 083 syllabus for 2026-27 is the stack, implemented using a list. Queues, linked lists and trees are not listed. Older books may include queues, so check the year before you spend time on them.

What is the difference between push and pop?

Push adds a new item on the top of the stack and pop removes the item on the top. With a Python list, push is stack.append(item) and pop is stack.pop(). Pop should be done only after checking that the stack is not empty.

What are overflow and underflow in a stack?

Overflow means an attempt to push when the stack is full. Underflow means an attempt to pop when it is empty. A Python list has no fixed size, so overflow matters only if the question sets a limit, but underflow must always be checked.

Why is LIFO used for a stack?

Because only one end is open. The item placed last lies on the top and covers the rest, so it has to leave before anything below it can. Undo and the browser back button need exactly this order: the most recent action is dealt with first.

Can I use insert(0) and pop(0) for a stack?

Yes, if you use both, because then the top is at index 0 and items still come out last in, first out. Do not mix them with append(), or you get first in, first out, which is not a stack. The append() and pop() pair is simpler.

How do I pop all elements from a stack in Python?

Use a while loop that runs as long as the stack is not empty, such as while stack: followed by print(stack.pop()). Do not use a for loop over the same list, since removing items while looping over it leaves some behind. Print the final message after the loop.

Is infix to postfix conversion in the Class 12 syllabus?

It is not named in the CBSE 083 syllabus for 2026-27, which lists the stack, the operations push and pop, and implementation using a list. Some books still explain it as an application of stacks. Your board preparation is better spent on push and pop from different kinds of data.

Can someone teach me stack programs one to one?

Yes. Our live classes for Class 12 CS are one to one, on the days and at the timing you want. You can book a priority demo, a full class of about 45 to 60 minutes followed by a written skill report, with its fee adjusted in your first month, or come to the free demo class.

Start

Write one push and pop pair with us.

That is the plan for the free demo class: one question, two functions, and a look at where your first attempt stops working.

Want a longer test? Reserve a priority demo for a time you like. The full class covers the stack from several kinds of data, and you are told in a written skill report what is secure and what is not. Its fee goes towards month one when you enrol.

Planning the weeks to 31 March 2027? The Class 12 CS revision plan shows where this chapter fits.

WhatsApp us · +91 91233 66161 · connect@modernagecoders.com

Every class is live video. The form requests a callback and reserves nothing.

We call within a few hours. No card, no enrolment fee.

Want it sooner? Book a priority demo

A full live class of about 45 to 60 minutes at a slot you pick, with a written skill report and learning roadmap on WhatsApp afterwards. The fee is adjusted against your first month if you enrol.

Book a priority demo

Keep exploring Modern Age Coders

By class and age

Learn more

Free resources

From the blog

Start here