Push, Pop & Peek Functions
The other kind of board question hands the stack to your functions as a parameter — push_book(BooksStack, new_book) — and asks for three small functions instead of two: push, pop, and one more that peeks, checks or displays. They are the functions from Writing the Stack Functions, with the board's names on them. The skill here is reading exactly what each one must print and what it must return.
def blocks are the answer.11 · A stack of books: push_book, pop_book and peep
A stack BooksStack holds book records, each a list of [book_title, author_name, publication_year]. Write (I) push_book(BooksStack, new_book) to push a new record; (II) pop_book(BooksStack) to pop the topmost record and return it, displaying “Underflow” if the stack is empty; (III) peep(BooksStack) to display the topmost element without deleting it, displaying ‘None’ if the stack is empty.(CBSE sample paper 2024-25 · 3 marks)
def push_book(BooksStack, new_book):
BooksStack.append(new_book)
def pop_book(BooksStack):
if len(BooksStack) == 0:
print('Underflow')
else:
return BooksStack.pop()
def peep(BooksStack):
if len(BooksStack) == 0:
print('None')
else:
print(BooksStack[-1])
books = []
push_book(books, ['Godan', 'Premchand', 1936])
push_book(books, ['Wings of Fire', 'A. P. J. Abdul Kalam', 1999])
peep(books)
print(pop_book(books))
print(pop_book(books))
print(pop_book(books))
peep(books)['Wings of Fire', 'A. P. J. Abdul Kalam', 1999] ['Wings of Fire', 'A. P. J. Abdul Kalam', 1999] ['Godan', 'Premchand', 1936] Underflow None None
return BooksStack.pop()pop_book must RETURN the record, so it hands it back rather than printing it. The calls at the bottom print what came back.
print('Underflow')On an empty stack there is nothing to return. The function prints its message and ends, so the caller receives None — the Underflow and the None in the run are two different lines from two different places.
print(BooksStack[-1])peep must DISPLAY, so here it prints. [-1] reads the top and removes nothing.
print('None')The question says to display 'None', in quotes — so this prints the word None. It is not returning the value None.
return. “Displays it” means print(). In this one question, pop_book returns and peep displays. Swapping them loses marks even though the program still runs.22 · A stack of colours: push_Clr, pop_Clr and isEmpty
A stack ClrStack holds colour records, each a tuple (ColorName, RED, GREEN, BLUE) such as ('Yellow', 237, 250, 68). Write (i) push_Clr(ClrStack, new_Clr) to push a new record; (ii) pop_Clr(ClrStack) to pop the topmost record and return it, displaying “Underflow” if the stack is empty; (iii) isEmpty(ClrStack) to return True if the stack is empty, and False otherwise.(CBSE 2025 board paper · 3 marks)
def push_Clr(ClrStack, new_Clr):
ClrStack.append(new_Clr)
def pop_Clr(ClrStack):
if isEmpty(ClrStack):
print('Underflow')
else:
return ClrStack.pop()
def isEmpty(ClrStack):
if len(ClrStack) == 0:
return True
else:
return False
colours = []
push_Clr(colours, ('Yellow', 237, 250, 68))
push_Clr(colours, ('Teal', 0, 128, 128))
print(isEmpty(colours))
print(pop_Clr(colours))
print(pop_Clr(colours))
print(isEmpty(colours))
pop_Clr(colours)False
('Teal', 0, 128, 128)
('Yellow', 237, 250, 68)
True
Underflowif isEmpty(ClrStack):pop_Clr uses isEmpty, which is written BELOW it. That is fine: a def only stores a function, and by the time pop_Clr is first called, every def in the file has run.
return True / return FalseisEmpty must return, not print. The program prints what it returns — False while two colours are there, True once they are gone.
pop_Clr(colours)The last call is not inside print(), so the None it hands back is simply dropped. Only the Underflow message shows.
33 · The last five: push_trail, pop_one and display_all
Write (i) push_trail(N, myStack), which pushes the last 5 elements of the list N onto myStack — for [1, 2, 3, 4, 5, 6, 7] the stack becomes [3, 4, 5, 6, 7]; (ii) pop_one(myStack), which pops and returns an element, or displays ‘Stack Underflow’ and returns None if the stack is empty; (iii) display_all(myStack), which displays every element without deleting them, or ‘Empty Stack’ if there are none.(CBSE 2025 board paper, alternative to question 2 · 3 marks)
def push_trail(N, myStack):
for x in N[-5:]:
myStack.append(x)
def pop_one(myStack):
if len(myStack) == 0:
print('Stack Underflow')
return None
else:
return myStack.pop()
def display_all(myStack):
if len(myStack) == 0:
print('Empty Stack')
else:
for i in range(len(myStack) - 1, -1, -1):
print(myStack[i])
N = [1, 2, 3, 4, 5, 6, 7]
s = []
push_trail(N, s)
print('stack :', s)
display_all(s)
print('popped:', pop_one(s))
print('stack :', s)
empty = []
display_all(empty)
print(pop_one(empty))stack : [3, 4, 5, 6, 7] 7 6 5 4 3 popped: 7 stack : [3, 4, 5, 6] Empty Stack Stack Underflow None
N[-5:]A slice from the fifth-last item to the end — [3, 4, 5, 6, 7]. Pushing them in that order leaves 7 on top, matching the question's stack.
return NoneThis question asks for it in words, so it is written out. Leaving it off would return None anyway, but writing it shows the examiner you read that part.
range(len(myStack) - 1, -1, -1)Displays top first and deletes nothing, as the question requires. A loop of pop() would print the same numbers and empty the stack.
N[-5:] is not the only way. for i in range(len(N) - 5, len(N)): with myStack.append(N[i]) pushes the same five items, and is just as correct.
44 · Even numbers: push_even, pop_even and Disp_even
Write push_even(N) to push every even integer in the list N onto a stack EvenNumbers; pop_even() to pop the topmost number and return it, displaying “Empty” if the stack is empty; and Disp_even() to display all elements without deleting them, displaying ‘None’ if the stack is empty. For [10, 5, 8, 3, 12] the stack should store [10, 8, 12].(CBSE sample paper 2024-25, alternative to question 1 · 3 marks)
EvenNumbers = []
def push_even(N):
for n in N:
if n % 2 == 0:
EvenNumbers.append(n)
def pop_even():
if len(EvenNumbers) == 0:
print('Empty')
else:
return EvenNumbers.pop()
def Disp_even():
if len(EvenNumbers) == 0:
print('None')
else:
for i in range(len(EvenNumbers) - 1, -1, -1):
print(EvenNumbers[i])
VALUES = [10, 5, 8, 3, 12]
push_even(VALUES)
print(EvenNumbers)
Disp_even()
print('popped:', pop_even())
print(EvenNumbers)[10, 8, 12] 12 8 10 popped: 12 [10, 8]
This question mixes both shapes. push_even(N) takes the data as a parameter, but the stack is the global EvenNumbers named in the question — so pop_even() and Disp_even() have empty brackets and use it by name.
55 · Using a stack to reverse a string
Write a function reverse(text) that uses a stack to return text written backwards.
def reverse(text):
stack = []
for ch in text:
stack.append(ch)
result = ''
while len(stack) > 0:
result = result + stack.pop()
return result
print(reverse('PYTHON'))
print(reverse('LambdaLab'))NOHTYP baLadbmaL
Every character goes on in order, so the last character ends up on top. Popping then hands them back last-first, and joining them builds the reversed word. Pre-board papers set this as an Assertion–Reason question — “a stack is used to reverse a string, because a stack follows LIFO order” — and both halves are true.
text[::-1] reverses a string in one step. When a question says using a stack, it wants the push and pop version, because the stack is what it is testing.6Run one yourself
7What to remember
Returns means return. Displays means print(). Read each function's line in the question separately.
In quotes it is a word to print. Without quotes it is the value to hand back.
if len(stack) == 0 — or isEmpty(stack) when the question asks you to write it.
Loop the positions from the top down. Never pop inside a display function.
pop_Clr can use isEmpty written below it, because both defs have run before either is called.
- 1
Add a
peep_Clr(ClrStack)to program 2 that returns the top colour's name only, or None when empty.Hint ·
ClrStack[-1][0]— the top record, then its first item. - 2
Write
push_head(N, myStack), which pushes the first 3 elements ofN.Hint ·
N[:3]. - 3
Use a stack to check whether a word is a palindrome.
Hint · Reverse it with the stack, then compare the result with the original.
- 4
Write
count_books(BooksStack, year), which returns how many books were published beforeyear, without changing the stack.Hint · A plain
forloop that only reads, and a counter.
pop_book() prints 'Underflow' when the stack is empty and has no return there. What does print(pop_book([])) show?
N = [1, 2, 3, 4, 5, 6, 7]. What is N[-5:]?
pop_Clr() calls isEmpty(), and isEmpty() is written below pop_Clr() in the file. What happens when pop_Clr() is called at the bottom of the program?
The question says peep() should 'display None if the stack is empty'. Which line fits?