Write a Python program to implement a stack using list.

“Write a Python program to implement a stack using a list” is a standard Class 11 and Class 12 computer science practical. A stack stores data so that the last item added is the first item removed, and a Python list is enough to build one. In this post you will get the complete menu-driven program, a version with functions, two classic uses of a stack (reversing a word and checking brackets), a class-based version with overflow and underflow, a step-by-step dry run, common mistakes with real error messages, practice questions and an FAQ. Use the interactive tool below to push, pop and peek on your own values and watch the list change.

📚 Stack Using a List in Python

Push, pop and peek on a stack, and watch the list change step by step.

Graphical view

Python code

Output

What You Will Learn

Problem Statement

Write a Python program to implement a stack using a list.

The program must support these operations: push (add an element on the top), pop (remove the top element), peek (see the top element without removing it) and display (show all the elements). It must also handle an empty stack properly by printing Stack Underflow instead of crashing.

What a Stack Is and How a List Works as a Stack

A stack is like a pile of plates. You put a new plate on the top, and you also take a plate from the top. The plate that went in last comes out first, so a stack follows the rule LIFO: Last In, First Out.

Python has no built-in stack, but a list can act as one. We decide that the end of the list is the top of the stack. Then every stack operation is one list operation:

Stack operationPython statementWhat it does
Create an empty stackstack = []Makes an empty list
push(item)stack.append(item)Adds the item at the end (the top)
pop()stack.pop()Removes and returns the last item
peek()stack[-1]Reads the last item, removes nothing
is empty?len(stack) == 0True when there are no items
sizelen(stack)Number of items

Before you pop or peek, you must check that the stack is not empty. Popping from an empty stack is called stack underflow. Pushing into a stack that is already full is called stack overflow. A Python list grows by itself, so overflow only exists if you set a size limit.

The Programs

Program 1: Menu-driven stack

Logic:

  • Create an empty list stack.
  • Repeat forever with while True: print the menu and read the choice.
  • 1 (Push): read the item and use append().
  • 2 (Pop): if the list is empty, print Stack Underflow. Otherwise print the value returned by pop().
  • 3 (Peek): if the list is empty, print a message. Otherwise print stack[-1].
  • 4 (Display): print the elements from the top to the bottom, that is from the last index to index 0.
  • 5 (Exit): leave the loop with break. Any other number prints Invalid choice.
stack = []
while True:
    print("1. Push  2. Pop  3. Peek  4. Display  5. Exit")
    choice = int(input("Enter your choice: "))
    if choice == 1:
        item = int(input("Enter the item to push: "))
        stack.append(item)
        print("Pushed", item)
    elif choice == 2:
        if len(stack) == 0:
            print("Stack Underflow")
        else:
            print("Popped", stack.pop())
    elif choice == 3:
        if len(stack) == 0:
            print("Stack is empty")
        else:
            print("Top element:", stack[-1])
    elif choice == 4:
        if len(stack) == 0:
            print("Stack is empty")
        else:
            print("Stack from top to bottom:")
            for i in range(len(stack) - 1, -1, -1):
                print(stack[i])
    elif choice == 5:
        print("Program ended")
        break
    else:
        print("Invalid choice")

Output (the user typed: 1 10, 1 20, 1 30, 4, 2, 3, 2, 2, 2, 3, 9, 5):

1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 1
Enter the item to push: 10
Pushed 10
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 1
Enter the item to push: 20
Pushed 20
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 1
Enter the item to push: 30
Pushed 30
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 4
Stack from top to bottom:
30
20
10
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 2
Popped 30
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 3
Top element: 20
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 2
Popped 20
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 2
Popped 10
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 2
Stack Underflow
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 3
Stack is empty
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 9
Invalid choice
1. Push  2. Pop  3. Peek  4. Display  5. Exit
Enter your choice: 5
Program ended

Program 2: Stack with functions

This is the same stack written as four small functions. It is the version shown step by step in the interactive tool above.

stack = []
 
def push(item):
    stack.append(item)
    print("Pushed", item)
 
def pop():
    if len(stack) == 0:
        print("Stack Underflow")
    else:
        item = stack.pop()
        print("Popped", item)
 
def peek():
    if len(stack) == 0:
        print("Stack is empty")
    else:
        print("Top element:", stack[-1])
 
def display():
    print("Stack:", stack)
 
push(10)
push(20)
push(30)
pop()
peek()
display()

Output:

Pushed 10
Pushed 20
Pushed 30
Popped 30
Top element: 20
Stack: [10, 20]

Dry Run

Take Program 2. The list changes like this:

Statementstack (end = top)Printed
stack = [][]
push(10)[10]Pushed 10
push(20)[10, 20]Pushed 20
push(30)[10, 20, 30]Pushed 30
pop()[10, 20]Popped 30
peek()[10, 20]Top element: 20
display()[10, 20]Stack: [10, 20]

Notice that 30 was the last element pushed and the first one popped. That is LIFO. The peek() line did not change the list.

Uses of a Stack

Reverse a word

Push every letter, then pop them all. The letters come out in the opposite order.

word = "HELLO"
stack = []
for ch in word:
    stack.append(ch)
rev = ""
while len(stack) > 0:
    rev += stack.pop()
print("Reversed:", rev)

Output:

Reversed: OLLEH

Check balanced brackets

Push every opening bracket. For every closing bracket, pop the top and check that it is the matching opening bracket. The expression is balanced if no mismatch happens and the stack is empty at the end.

expr = input("Enter brackets: ")
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
balanced = True
for ch in expr:
    if ch in "([{":
        stack.append(ch)
    elif ch in ")]}":
        if len(stack) == 0:
            balanced = False
            break
        if stack.pop() != pairs[ch]:
            balanced = False
            break
if len(stack) != 0:
    balanced = False
if balanced:
    print("Balanced")
else:
    print("Not balanced")

We ran the program with each of these inputs:

InputOutputWhy
{[()]}BalancedEvery closing bracket matches the top of the stack and the stack ends empty.
([)]Not balancedThe ) finds [ on the top, which does not match.
((()Not balancedThe stack still holds opening brackets at the end.
())Not balancedThe last ) finds an empty stack.

Class-based stack with overflow and underflow

Some practicals ask for a stack with a fixed size. Here the size is 3, so the fourth push gives Stack Overflow.

class Stack:
    def __init__(self, size):
        self.items = []
        self.size = size
 
    def is_empty(self):
        return len(self.items) == 0
 
    def is_full(self):
        return len(self.items) == self.size
 
    def push(self, item):
        if self.is_full():
            print("Stack Overflow")
        else:
            self.items.append(item)
            print("Pushed", item)
 
    def pop(self):
        if self.is_empty():
            print("Stack Underflow")
            return None
        return self.items.pop()
 
    def peek(self):
        if self.is_empty():
            return None
        return self.items[-1]
 
 
s = Stack(3)
s.push(1)
s.push(2)
s.push(3)
s.push(4)
print("Top:", s.peek())
print("Popped:", s.pop())
print("Popped:", s.pop())
print("Popped:", s.pop())
print("Popped:", s.pop())
print("Empty:", s.is_empty())

Output:

Pushed 1
Pushed 2
Pushed 3
Stack Overflow
Top: 3
Popped: 3
Popped: 2
Popped: 1
Stack Underflow
Popped: None
Empty: True

Common Mistakes

  • Popping from an empty list: stack.pop() stops with IndexError: pop from empty list. Check len(stack) == 0 first.
  • Peeking at an empty list: stack[-1] stops with IndexError: list index out of range.
  • Using pop(0): pop(0) removes the first element. For [1, 2, 3] it returns 1 and leaves [2, 3]. That is a queue, not a stack. A stack uses pop() with no number.
  • Forgetting to check the stack in peek: always test for an empty stack before reading the top.
  • Printing the list as the stack from the top: print(stack) shows the bottom element first. To show from the top, loop from len(stack) - 1 down to 0, as in Program 1.
  • Using a variable named list: it hides the built-in list. Use stack.

Practice Questions

  1. Convert a decimal number to binary using a stack.
  2. Write a program that checks whether a string is a palindrome using a stack.
  3. Add a size() and an is_empty() function to Program 2.
  4. Push the numbers 1 to 5, then pop all of them and print them. In what order do they appear?
  5. Write a program with a stack of student names and a menu to add and remove a name.

Frequently Asked Questions

What is a stack in Python?

A stack is a data structure that follows the LIFO rule: Last In, First Out. The element added last is removed first. Python has no separate stack type, but a list works as a stack when you add and remove only at its end.

How do you implement a stack using a list in Python?

Create an empty list with stack = []. Push with stack.append(item), pop with stack.pop(), and look at the top with stack[-1]. The end of the list is the top of the stack.

What does push do in a stack?

Push adds a new element on the top of the stack. In a list-based stack it is append(), which adds the element at the end of the list.

What does pop do, and what happens if the stack is empty?

Pop removes and returns the top element. If the list is empty, stack.pop() stops the program with IndexError: pop from empty list. So always check len(stack) == 0 first and print Stack Underflow.

What is peek (or top) in a stack?

Peek shows the top element without removing it. In Python it is stack[-1]. On an empty list it raises IndexError: list index out of range, so check for an empty stack first.

What is the difference between stack underflow and overflow?

Underflow happens when you pop from an empty stack. Overflow happens when you push into a stack that is already full. A Python list can grow as needed, so overflow only happens if you set a size limit yourself, as in the class-based program above.

Why is the end of the list used as the top?

Adding and removing at the end of a list is fast, because no other element has to move. If you use the start of the list with insert(0, item) and pop(0), every element shifts one place, which is slower for big stacks.

What is the difference between a stack and a queue?

A stack is LIFO: the last element in is the first out. A queue is FIFO: the first element in is the first out. Calling pop(0) on the list removes the oldest element, which is queue behaviour, not stack behaviour.

Where are stacks used in real life?

Stacks are used for the undo button in editors, the back button in a browser, checking brackets in expressions, reversing a string and keeping track of function calls (the call stack). A pile of plates is the usual picture: you add and remove from the top.

How do I write the menu-driven stack program for the practical file?

Use a while True loop that prints the menu, reads the choice and calls push, pop, peek, display or exit with break. Program 1 above is a complete, tested version.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top