Stack in Python: CBSE Class 12 Computer Science Notes and Programs
Updated 14 October 2026 · Fact-checked
A stack is a linear data structure in which items are added and removed at one end only, called the top, so the last item pushed is the first popped (LIFO). In Class 12 you implement it with a Python list: append() pushes, pop() pops, and an empty-list check prevents underflow.
What Stack is about
Stack is the last chapter of Unit 1. It is small in theory, but the 2026-27 sample paper gives it a 3-mark question in Section C: "write functions to push items that satisfy a condition onto a stack and to pop and display them". MCQs and assertion-reason items test LIFO order and the meaning of underflow.
The syllabus wording is "Data Structure: Stack, operations on stack (push & pop), implementation of stack using list". So you need:
- what a data structure is and why a stack is a linear, LIFO structure
- real uses of a stack: undo, the browser back button, reversing a string, matching brackets, and the way function calls return
- push (add at the top) and pop (remove from the top), with overflow and underflow
- helper operations: peek/top (see the top item without removing it), isEmpty and size
- the list implementation: the end of the list is the top,
append()is push,pop()is pop,L[-1]is peek,len(L) == 0is the empty test
NCERT sections 3.5-3.7 on infix and postfix notation are not in the 2026-27 syllabus and are left out here. Queues, sorting and searching are separate NCERT chapters that are also outside the syllabus.
Weightage: This chapter is part of Unit 1, Computational Thinking and Programming - 2, which carries 40 of the 70 theory marks together with Revision of Python Topics from Class XI, Functions, Exception Handling in Python and File Handling in Python.Source: CBSE Computer Science (083) syllabus 2026-27, distribution of marks, Unit 1 Computational Thinking and Programming - 2
Key concepts
- Data structures and the stack
- NCERT section NCERT 3.1, 3.2
A data structure is a way of organising data in memory so that certain operations are easy, for example a list, a tuple or a dictionary. A stack is a linear data structure in which insertion and deletion happen at the same end, called the top. The item that went in last comes out first: LIFO (Last In, First Out). Think of a pile of plates: you put a plate on the top and take the top plate off; you cannot pull one out from the middle.
Worked example
Books are placed on a pile in the order Physics, Chemistry, Maths, CS. Two books are taken off. Which books remain, and which is now on top?
Try it first, then show the solutionSolution
- The pile is a stack; CS went on last, so it is on top.
- Two removals take CS, then Maths (LIFO).
- Physics and Chemistry remain; Chemistry is on top.
Answer: Physics and Chemistry remain; Chemistry is on top.
- Applications of a stack
- NCERT section NCERT 3.2.1
A stack is used wherever the latest action must be handled first: the undo feature of a text editor (the last change is undone first), the back button of a web browser (the last page visited is shown first), reversing a string or list (push all, then pop all), checking whether brackets are balanced in an expression, and the way a program keeps track of function calls (the function called last returns first).
Worked example
Use a stack to reverse the string 'CBSE'.
Try it first, then show the solutionSolution
- Push each character: the stack holds C, B, S, E with E on top.
s = [] for ch in 'CBSE': s.append(ch) r = '' while s: r += s.pop() print(r)- Pop until empty: E, S, B, C.
Answer: ESBC
- Push and pop; overflow and underflow
- NCERT section NCERT 3.3, 3.3.1
Push adds an item at the top; pop removes and returns the top item. Trying to pop from an empty stack is underflow; trying to push onto a stack that is full (when the stack has a fixed size) is overflow. A Python list grows as needed, so with a list only underflow is a practical concern:
[].pop()raises IndexError: pop from empty list, so a pop function must check for an empty stack first.Worked example
Starting with an empty stack, perform: push 5, push 8, pop, push 3, push 9, pop, pop, push 1. Show the stack (bottom to top) at the end and the popped items in order.
Try it first, then show the solutionSolution
- push 5: [5]; push 8: [5, 8]; pop removes 8: [5].
- push 3: [5, 3]; push 9: [5, 3, 9]; pop removes 9; pop removes 3: [5].
- push 1: [5, 1].
Answer: Final stack [5, 1] (1 on top); popped in order: 8, 9, 3.
- Implementing a stack with a Python list
- NCERT section NCERT 3.4
Take the end of the list as the top. Then every operation is quick and simple:
Operation Python create stack = []push x stack.append(x)pop stack.pop()(only if not empty)peek / top stack[-1](only if not empty)isEmpty len(stack) == 0(ornot stack)size len(stack)Using the front of the list as the top (
insert(0, x)andpop(0)) also works but is slower and easy to get wrong, so the board's answers use the end.Worked example
Write isEmpty(st) and peek(st), where peek returns the top item, or 'Underflow' if the stack is empty. What do peek([]) and peek([4, 7]) return?
Try it first, then show the solutionSolution
def isEmpty(st): return len(st) == 0 def peek(st): if isEmpty(st): return 'Underflow' return st[-1] print(peek([]), peek([4, 7]))- [] is empty, so 'Underflow'; in [4, 7] the top is the last item, 7.
Answer: Underflow 7
- Board pattern: push items that meet a condition, then pop all
- NCERT section NCERT 3.4 (Program 3-1 pattern)
The usual 3-mark question gives a list, tuple or dictionary and asks for two functions: one that pushes only the items meeting a condition, and one that pops and displays items until the stack is empty, then prints a message such as 'Stack Empty'. Write the stack as a global list or pass it as a parameter, exactly as the question says. Pop in a
whileloop (while st:orwhile len(st) != 0:), not aforloop over the stack, because the stack shrinks while you pop.Worked example
Write PushEven(N, st) to push the even numbers of list N onto stack st, and PopEven(st) to pop and display them, then print 'Stack Empty'. Show the output for N = [12, 7, 18, 5, 4].
Try it first, then show the solutionSolution
def PushEven(N, st): for x in N: if x % 2 == 0: st.append(x) def PopEven(st): while st: print(st.pop(), end=' ') print('Stack Empty') S = [] PushEven([12, 7, 18, 5, 4], S) print(S) PopEven(S)- Even numbers pushed in order: 12, 18, 4 (4 on top).
- Popping gives them in reverse: 4, 18, 12.
Answer: [12, 18, 4]
4 18 12 Stack Empty- Stacks of records
- NCERT section NCERT 3.4
A stack item can be any object: a number, a string, a list or a tuple. Board questions often push a part of a record, for example the name and price of each book costing more than 400, taken from a list of tuples or from a dictionary. Build the item first (
[b[0], b[1]]) and push it as one element; popping returns the whole item.Worked example
books = [('B1', 'Python', 450), ('B2', 'SQL', 300), ('B3', 'Networks', 520)]. Push [code, title] for each book priced above 400, then pop and print each, and print 'Empty' at the end.
Try it first, then show the solutionSolution
books = [('B1', 'Python', 450), ('B2', 'SQL', 300), ('B3', 'Networks', 520)] BS = [] for b in books: if b[2] > 400: BS.append([b[0], b[1]]) while BS: print(BS.pop()) print('Empty')- Pushed: ['B1', 'Python'], then ['B3', 'Networks'] (top).
- Popped: B3 first, then B1.
Answer: ['B3', 'Networks']
['B1', 'Python']
Empty
Stack in real life
Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Undo as a stack
Suppose a drawing app stores each action in a list as it happens: ['line', 'circle', 'fill', 'text'], and the user presses Undo twice.
Which actions are undone, in which order, and what is left?
Try it first, then show the solutionSolution
- The actions list is a stack with 'text' on top.
- The first Undo pops 'text'; the second pops 'fill'.
Answer: 'text' and then 'fill' are undone; ['line', 'circle'] remain.
Memory hook: Undo always takes back the latest change: that is LIFO.
Browser back button
Imagine you open the school website, then the CS page, then the syllabus PDF, and press Back once.
Model the history as a stack and say which page is shown after one Back.
Try it first, then show the solutionSolution
- Pushes: home, cs, syllabus (top).
- Back pops 'syllabus'; the new top, 'cs', is shown.
Answer: The CS page.
Memory hook: Back = pop; the page under it reappears.
Balanced brackets
Suppose a code editor highlights a missing bracket by checking each '(' and ')' as you type.
Write balanced(s) that uses a stack to check whether the round brackets in s are balanced, and test it on '(a+(b*c))', '(a+b))(' and '((a)'.
Try it first, then show the solutionSolution
- Push on '('; on ')' pop, but if the stack is already empty the brackets are unbalanced. At the end the stack must be empty.
def balanced(s): st = [] for ch in s: if ch == '(': st.append(ch) elif ch == ')': if not st: return False st.pop() return len(st) == 0 print(balanced('(a+(b*c))'), balanced('(a+b))('), balanced('((a)'))
Answer: True False False
Memory hook: Every ')' must find a '(' waiting on top of the stack.
Topics in this chapter
- Conditional Push and Pop ProgramsComing soon
- Push and Pop OperationsComing soon
- Implementing a Stack Using a ListComing soon
- Stack Programs: Conditional Push and Pop All
- Push and Pop Operations on a Stack Using a List
- Stack: LIFO Principle and Applications
Stack: syntax and key facts
- Stack principle
- LIFO: Last In, First Out; all insertions and deletions at the top
- Contrast: a queue is FIFO (not in the 2026-27 syllabus).
- List operations
- push
st.append(x); popst.pop(); peekst[-1]; emptylen(st) == 0; sizelen(st) - The end of the list is the top.
- Underflow and overflow
- Underflow: pop or peek on an empty stack. Overflow: push on a full fixed-size stack.
[].pop()raises IndexError: pop from empty list.- Pop-all loop
while st:/while len(st) != 0:thenprint(st.pop()); after the loop print the empty message- Never pop inside
for x in st:; the list shrinks while you loop.
How the board asks Stack
The question patterns to expect, and the method that works for each.
| Question type | How it is asked | Method |
|---|---|---|
| Push-pop functions on a list, tuple or dictionary | "Write PUSH(...) to push ... that satisfy ... and POP(...) to pop and display them; print 'Stack Empty'/'None' when empty" (3 marks, Section C). | Copy the function names and parameters; loop over the data and append when the condition holds; pop in a while loop; print the message after the loop. |
| Trace a sequence of operations | Given pushes and pops, show the stack or the popped items (1-2 marks). | Write the stack bottom-to-top after every operation; the item removed by pop is always the rightmost. |
| Definitions and applications | What is a stack, LIFO, underflow? Give two applications (1-2 marks). | One-line definition plus a real example such as undo or browser back. |
| Assertion-reason and MCQ | Statements on LIFO order, underflow, or which list method implements push or pop. | Remember: push = append (end), pop = pop() (end), peek = [-1]. |
| Find the output of a stack program | A function that pushes or pops under conditions and prints (2 marks). | Trace the list after each append and pop; note the order of printing is reverse of pushing. |
Tricks to remember Stack
Short memory aids. Say each one aloud once, then use it on a question the same day.
LIFO = plates in the canteen
The last plate washed goes on top and is the first one picked up.
Use it when: Defining a stack and tracing pushes and pops.
append is push, pop is pop
Python already names one of the two operations for you; the other is append().
Use it when: Writing the list implementation quickly.
Under = nothing under your hand
Underflow: you reach for the top plate and there is none. Overflow: the shelf is full.
Use it when: Defining underflow and overflow.
Pop with while, never with for
"While there is something, take it" - while st: st.pop().
Use it when: The pop-and-display function.
Stack: board-level solved questions
Ordered from board level to HOTS. Cover the solution, write your own, then compare step by step.
Example 1: Dictionary to stack · 3 marks · Short answerBoard level
D = {'Asha': 88, 'Ravi': 64, 'Meena': 79, 'Joy': 91}. Write push_high(D) to push the names with marks above 75 onto a global stack stk, and pop_all() to pop and display them and then display 'None'. Give the output.
Try it first, then show the solutionSolution
D = {'Asha': 88, 'Ravi': 64, 'Meena': 79, 'Joy': 91} stk = [] def push_high(D): for k in D: if D[k] > 75: stk.append(k) def pop_all(): while len(stk) != 0: print(stk.pop(), end=' ') print('None') push_high(D) print(stk) pop_all()- Pushed in dictionary order: Asha, Meena, Joy (Ravi has 64).
- Popped in reverse: Joy, Meena, Asha.
Answer: ['Asha', 'Meena', 'Joy']
Joy Meena Asha None
Example 2: Trace with conditions · 2 marks · Short answerHarder board level
Predict the output:
st = []
for n in [4, 9, 16, 25, 36]:
if n % 2 == 0:
st.append(n)
elif st:
st.pop()
print(st)Try it first, then show the solutionSolution
- 4 even: push → [4].
- 9 odd and the stack is not empty: pop → [].
- 16 even: [16]. 25 odd: pop → []. 36 even: [36].
Answer: [36]
Example 3: Stack or queue? · 1 mark · MCQHOTS / competency
A programmer implements a 'stack' with st.append(x) for push and st.pop(0) for pop. After pushing 1, 2, 3, which value does the first pop return? (a) 3 (b) 1 (c) 2 (d) IndexError
Try it first, then show the solutionSolution
- append adds at the end: [1, 2, 3].
- pop(0) removes from the front: 1. This is FIFO, so the structure behaves like a queue, not a stack.
Answer: (b) 1 (the implementation is wrong for a stack)
Example 4: Assertion-reason on underflow · 1 mark · Assertion-reasonHOTS / competency
Assertion (A): A stack implemented with a Python list can face underflow but practically never overflow.
Reason (R): A Python list grows dynamically as items are appended.
(a) Both true, R explains A (b) Both true, R does not explain A (c) A true, R false (d) A false, R true
Try it first, then show the solutionSolution
- Popping from an empty list fails, so underflow can happen.
- A list has no fixed size, so it does not fill up; R gives that reason.
Answer: (a) Both A and R are true and R is the correct explanation of A.
Example 5: Books stack with one-at-a-time pop · 5 marks · Long answerHarder board level
A list of tuples holds (code, title, price). Write PUSH_COSTLY(books, st) to push [code, title] of books priced above 400, and POP_COSTLY(st) to pop and return one item, or return 'Empty' if the stack is empty. Show three calls of POP_COSTLY after pushing from [('B1', 'Python', 450), ('B2', 'SQL', 300), ('B3', 'Networks', 520)].
Try it first, then show the solutionSolution
def PUSH_COSTLY(books, st): for b in books: if b[2] > 400: st.append([b[0], b[1]]) def POP_COSTLY(st): if len(st) == 0: return 'Empty' return st.pop() S = [] PUSH_COSTLY([('B1', 'Python', 450), ('B2', 'SQL', 300), ('B3', 'Networks', 520)], S) print(POP_COSTLY(S)) print(POP_COSTLY(S)) print(POP_COSTLY(S))- Two items are pushed; the third pop finds the stack empty.
Answer: ['B3', 'Networks']
['B1', 'Python']
Empty
Example 6: Display a stack from the top · 2 marks · Short answerHarder board level
Write display(st) that prints the items of a stack from top to bottom without removing them, or 'Stack empty'. Show the call for [10, 20, 30].
Try it first, then show the solutionSolution
- Walk the list from the last index down to 0.
def display(st): if not st: print('Stack empty') else: for i in range(len(st) - 1, -1, -1): print(st[i]) display([10, 20, 30])
Answer: 30
20
10
Example 7: Push only vowels · 3 marks · Short answerHarder board level
Write PUSHV(word, st) that pushes every vowel of word onto stack st, and POPV(st) that pops and joins them into a string and returns it. What does POPV return after PUSHV('Education', S)?
Try it first, then show the solutionSolution
def PUSHV(word, st): for ch in word: if ch.lower() in 'aeiou': st.append(ch) def POPV(st): r = '' while st: r += st.pop() return r S = [] PUSHV('Education', S) print(POPV(S))- Vowels pushed: E, u, a, i, o (o on top).
- Popped and joined: o, i, a, u, E.
Answer: oiauE
Case-study practice (Section E style)
Read the situation, then answer every part. In the board paper this is a 4-mark question split into 1 + 1 + 2 marks.
Text editor undo
Suppose a simple text editor keeps every typed word on a stack named history, so that Undo can remove the most recent word. A user types the words 'Board', 'exams', 'are', 'near' in that order and then presses Undo once.
(i) · 1 mark
What is on the top of history before Undo?
Answer
Answer: 'near'
The last item pushed is on top.
(ii) · 1 mark
Which list method should Undo use?
Answer
Answer: pop()
pop() removes and returns the last item of the list, the top of the stack.
(iii) · 2 marks
Write a function undo(history) that removes the last word and returns it, or returns 'Nothing to undo' if history is empty. Show the result of one Undo and the remaining text joined with spaces.
Answer
Answer:
Output:def undo(history): if not history: return 'Nothing to undo' return history.pop() history = ['Board', 'exams', 'are', 'near'] print(undo(history)) print(' '.join(history))
near
Board exams areThe empty check prevents underflow; pop() removes 'near'; join() rebuilds the remaining text.
Where the marks are
How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.
Define a stack and explain underflow with an example. [2 marks] (2 marks)
| Step | Marks |
|---|---|
| Stack: a linear data structure where insertion and deletion take place only at the top, following LIFO | 1 |
| Underflow: trying to pop from an empty stack, e.g. calling pop() when stack = [] | 1 |
A dictionary D holds names and marks. Write push_high(D) to push the names of students with marks above 75 onto a stack stk, and pop_all() to pop and display them, then display 'None'. [3 marks] (3 marks)
| Step | Marks |
|---|---|
| push_high: loop over the dictionary with the condition D[k] > 75 | 1 |
| Pushing the name with stk.append(k) | 0.5 |
| pop_all: while loop until the stack is empty, popping and displaying | 1 |
| Displaying 'None' after the loop | 0.5 |
Write a menu-driven program for a stack of integers with options 1 Push, 2 Pop, 3 Peek, 4 Display (top to bottom), 5 Exit, handling underflow. [4 marks] (4 marks)
| Step | Marks |
|---|---|
| Menu loop reading the choice until 5 | 1 |
| Push reading a number and appending | 0.5 |
| Pop and Peek with an empty check and 'Underflow' message | 1.5 |
Display in reverse order (top first), e.g. for i in range(len(st) - 1, -1, -1) | 1 |
A list of tuples holds (code, title, price) of books. Write PUSH_COSTLY(books, st) to push [code, title] of books priced above 400, POP_COSTLY(st) to pop and display one item or 'Empty', and show the calls. [5 marks] (5 marks)
| Step | Marks |
|---|---|
| PUSH_COSTLY header and loop over the tuples | 1 |
| Condition b[2] > 400 and pushing [b[0], b[1]] | 1 |
| POP_COSTLY with the empty check | 1 |
| Popping and displaying the item | 1 |
| Correct calls and the stack passed as an argument | 1 |
Where students lose marks in Stack
The slips examiners see most often, and what to write instead.
Mistake: Popping without checking for an empty stack
pop() on an empty list raises IndexError, and the question usually asks for a message instead.
Wrong working
def POP(st):
return st.pop()Right working
def POP(st):
if len(st) == 0:
print('Underflow')
else:
return st.pop()Do this: Check
if st:(or len(st) == 0) before every pop or peek.Usually costs: Half to 1 mark
Mistake: Using pop(0) or insert(0, x) with append()
Mixing ends turns the stack into a queue: pop(0) removes the first item pushed (FIFO).
Wrong working
st.append(x) ... st.pop(0)
Right working
st.append(x) ... st.pop()
Do this: Use one end only: the end of the list.
Usually costs: 1 mark
Mistake: Popping inside a for loop over the same stack
The list shrinks while the for loop walks it, so about half the items are skipped.
Wrong working
for x in st:
print(st.pop())Right working
while st:
print(st.pop())Do this: Always pop in a while loop that runs until the stack is empty.
Usually costs: 1 mark
Mistake: Printing the message inside the loop or forgetting it
The question asks for 'Stack Empty' (or 'None') once, after all items are popped.
Do this: Put the message after the while loop, at the function's indentation level.
Usually costs: Half a mark
Mistake: Pushing the wrong part of a record
Questions such as "push the name and price of items above 400" need a two-item list or tuple, not the whole record or two separate pushes.
Do this: Build the item exactly as asked (e.g.
[rec[0], rec[2]]) and push it once.Usually costs: Half a mark
NCERT exercise guide: Stack
What each exercise in the NCERT chapter tests, how to approach it, and a question of the same kind solved step by step. Questions here are written in our own words.
NCERT Chapter 3 exercises: stack operations and applications (questions on 3.1-3.4 only)
What it tests: Tracing push and pop sequences, LIFO, applications, and writing the list-based push and pop functions.
How to approach it: Draw the stack after each step; for programs, use append and pop at the end of the list.
Same kind as the reverse-a-string exercise
Write a program that uses a stack to print the words of 'stack follows LIFO order' in reverse order.
Show the solutionSolution
st = [] for w in 'stack follows LIFO order'.split(): st.append(w) while st: print(st.pop(), end=' ')- The last word pushed, 'order', is popped first.
Answer: order LIFO follows stack
NCERT Chapter 3 exercises: postfix and infix questions
What it tests: Conversion and evaluation of expressions (NCERT 3.5-3.7).
How to approach it: Not in the 2026-27 CBSE syllabus; skip these exercises.
Same kind as the stack-trace exercise (the in-syllabus part)
Show the stack after each operation: push 'A', push 'B', pop, push 'C', push 'D', pop.
Show the solutionSolution
- ['A'] → ['A', 'B'] → pop B → ['A'] → ['A', 'C'] → ['A', 'C', 'D'] → pop D → ['A', 'C'].
Answer: Final stack ['A', 'C']; popped B and D.
Practice questions on Stack
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Which principle does a stack follow? (a) FIFO (b) LIFO (c) Random access (d) Sorted order
Hint
Pile of plates.
Answer
(b) LIFO
Q2 · 1 mark · Very short answerBoard level
Which list method is used to push an element onto a stack implemented as a list?
Hint
Adds at the end.
Answer
append()
Q3 · 1 mark · Very short answerBoard level
Show the stack (bottom to top) after: push 'X', push 'Y', push 'Z', pop, pop, push 'W'.
Hint
Z and then Y are removed.
Answer
['X', 'W']
Q4 · 3 marks · Short answerHarder board level
Write PushOdd(N) to push the odd numbers greater than 10 from list N onto a global stack ODD, and PopOdd() to pop and display them followed by 'Stack Underflow'. Show the output for N = [11, 4, 23, 7, 15].
Hint
Two conditions: odd and > 10.
Answer
ODD = [] def PushOdd(N): for x in N: if x % 2 == 1 and x > 10: ODD.append(x) def PopOdd(): while ODD: print(ODD.pop(), end=' ') print('Stack Underflow') PushOdd([11, 4, 23, 7, 15]) PopOdd()Output: 15 23 11 Stack Underflow
Q5 · 2 marks · Short answerHarder board level
Predict the output:
s = [1, 2, 3, 4] t = [] while s: x = s.pop() if x % 2 == 0: t.append(x * 10) print(s, t)Hint
Popping starts from 4.
Answer
[] [40, 20]
Q6 · 2 marks · Short answerHOTS / competency
A list of dictionaries holds {'name': ..., 'city': ...}. Write PUSH_CITY(L, st, c) that pushes the names of people from city c onto st. What is st after PUSH_CITY([{'name': 'A', 'city': 'Pune'}, {'name': 'B', 'city': 'Agra'}, {'name': 'C', 'city': 'Pune'}], S, 'Pune')?
Hint
Each item is a dictionary.
Answer
def PUSH_CITY(L, st, c): for d in L: if d['city'] == c: st.append(d['name']) S = [] PUSH_CITY([{'name': 'A', 'city': 'Pune'}, {'name': 'B', 'city': 'Agra'}, {'name': 'C', 'city': 'Pune'}], S, 'Pune') print(S)Output: ['A', 'C']
Q7 · 1 mark · Assertion-reasonHOTS / competency
Assertion (A): Popping items inside
for x in st:empties the stack completely.
Reason (R): Removing items from a list while a for loop walks it makes the loop skip items.Hint
Try it with 4 items.
Answer
(d) A is false but R is true: with [1, 2, 3, 4] only two pops happen, leaving [1, 2].
Q8 · 2 marks · Short answerBoard level
Give two real-life situations where a stack is used and explain why LIFO fits each.
Hint
Think of the most recent action.
Answer
Undo in an editor: the most recent change must be undone first. Browser back button: the page visited last is the first one to return to. (Other valid answers: reversing a word, bracket matching, function calls.)
Q9 · 3 marks · Short answerHOTS / competency
Write a program that uses a stack to check whether a word is a palindrome. Test with 'level' and 'stack'.
Hint
Popping gives the word reversed.
Answer
def is_pal(w): st = [] for ch in w: st.append(ch) rev = '' while st: rev += st.pop() return rev == w print(is_pal('level'), is_pal('stack'))Output: True False
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.What does LIFO stand for?Show answer
Last In, First Out.
2.Which end of a Python list is used as the top in the usual implementation?Show answer
The end (last item); push with append(), pop with pop().
3.What is underflow?Show answer
An attempt to pop (or peek) from an empty stack.
4.What does
[].pop()raise?Show answerIndexError: pop from empty list.
5.Give two applications of a stack.Show answer
Any two: undo in an editor, browser back button, reversing a string, matching brackets, function calls.
6.How do you see the top item without removing it?Show answer
st[-1](after checking that the stack is not empty).7.Push 1, 2, 3, then pop twice. What remains?Show answer
[1].
Best order to study it
- What a data structure is; stack and LIFO with a real example.
- Applications: undo, back button, reversal, bracket matching.
- Push, pop, underflow and overflow; trace operation sequences.
- List implementation: append, pop, [-1], len.
- Board pattern: conditional push from a list, tuple or dictionary, then pop-all with a message.
Quick revision checklist
The night before the exam: can you do each of these without looking?
- Stack: linear data structure; insert and delete at the top only; LIFO.
- Push adds at the top; pop removes and returns the top item.
- Underflow: pop/peek on an empty stack. Overflow: push on a full fixed-size stack.
- List as stack: top = end; append() push; pop() pop; st[-1] peek; len(st) == 0 empty.
[].pop()raises IndexError, so check before popping.- Pop all with
while st:and print the empty message after the loop. - Applications: undo, browser back, reversing, bracket matching, function calls.
Stack: frequently asked questions
Is infix to postfix conversion in the Class 12 CS syllabus for 2026-27?
No. The syllabus limits the stack to push and pop operations and implementation using a list. NCERT sections on notations for expressions, infix-to-postfix conversion and postfix evaluation are not in the 2026-27 syllabus.
Is the queue in the CBSE Class 12 syllabus?
No. Only the stack is listed under data structures. The NCERT chapters on queue, sorting and searching are not in the 2026-27 syllabus.
What type of stack question comes in the board exam?
In the 2026-27 sample paper it is a 3-mark Section C question: write a function that pushes items meeting a condition (from a list, tuple or dictionary) onto a stack and another that pops and displays them, showing a message when the stack is empty.
Why is there no overflow when a stack is a Python list?
A list grows automatically as long as memory is available, so it never becomes full in a school program. Overflow matters for a stack of fixed size.
Should the stack be a global variable or a parameter?
Follow the question. If it names a global stack (for example 'a stack named ST'), use that list; if the function header has the stack as a parameter, use the parameter.
Based on: CBSE Computer Science (083) syllabus 2026-27; NCERT Computer Science, Textbook for Class XII (Reprint 2026-27)