Python Program to Implement a Stack Using a List
Intermediate · Data structures · CBSE class 12 practical list
A stack is a data structure where the last item added is the first one removed (LIFO, last in first out), like a pile of plates. Adding an item is called push, removing the top item is called pop, and looking at the top item without removing it is called peek. This program builds a stack on a Python list and handles popping from an empty stack, which is called underflow.
Program
Pushed 10 Pushed 20 Pushed 30 Stack from top to bottom: [30, 20, 10] Top element: 30 Popped 30 Popped 20 Popped 10 Underflow: the stack is empty, nothing to pop The stack is empty
How it works
- The list
stackholds the items, and its last element is treated as the top of the stack. push()adds an item on top withappend(), andpop()uses the list methodpop(), which removes and returns the last item.- Before popping or peeking, the functions check
len(stack) == 0, because popping an empty list would crash with anIndexError; printing an underflow message instead is what the question asks for. peek()reads the top item withstack[-1]without removing it.display()printsstack[::-1], the list reversed, so the top of the stack comes first.
Another way to write it
A board exam style question: push only the multiples of 3
Stack after pushing: [12, 9, 33] Popped 33 Popped 9 Popped 12 Stack is empty
Board papers often ask for two functions like these: one pushes only the items that pass a test, and the other pops and prints until the stack is empty. The items come out in reverse order: 33, 9, 12.
Try it yourself
Give the stack a size limit of 3 and make push() print "Overflow" when the stack is already full.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises