-
Hajipur, Bihar, 844101
A stack is one of the simplest and most important data structures in programming. It works on the LIFO rule, which means Last In, First Out. The item you add last is the one that comes out first. This pattern appears everywhere in real systems, from undo features in apps to browser history, call operations in Python and even memory management.
In this chapter, you will understand what a stack is, how it works, how to build stacks using Python lists, how to implement them using the collections module and how stacks appear in real-world applications. You will also practice common operations such as push, pop, peek and checking if a stack is empty. The goal is to help you use stacks confidently in both small programs and larger data-handling tasks.
A stack is a linear data structure where elements are added and removed from the same end. This end is called the top of the stack.
A simple way to imagine a stack is a pile of plates. You place new plates on top and remove plates from the top. You cannot remove from the middle or bottom without disturbing the stack.
Stacks follow two main operations:
Push: Add an item to the top
Pop: Remove an item from the top
Every stack also allows checking the top element and checking whether the stack is empty.
LIFO stands for Last In, First Out. This rule decides how items move in and out of a stack.
Example scenario:
You push 10
You push 20
You push 30
Now the stack looks like this (top → bottom): 30, 20, 10
If you pop, you will get 30 first.
This makes stacks perfect for tasks where the most recent action needs to be undone or reversed.
The simplest way to create a stack in Python is to use a list. The append() method performs push and the pop() method performs pop.
stack = []
stack.append(10)
stack.append(20)
stack.append(30)
print(stack)
When you pop:
value = stack.pop()
print(value)
This removes the top element and returns it.
Push adds a new value at the end:
stack.append(40)
This is useful in tasks like saving browser history or adding steps in an undo feature.
Pop removes and returns the most recent value:
item = stack.pop()
This helps reverse processes, step back through changes or manage temporary operations.
Peek means checking the top element without removing it.
top = stack[-1]
print(top)
This is helpful when you need to inspect what is next without changing the stack.
Empty stacks help prevent errors during pop operations.
if not stack:
print("Stack is empty")
else:
print("Stack has items")
This is important for safe coding in programs where user input or external systems control flow.
While lists work well, Python’s deque from the collections module provides faster append and pop operations for large stacks.
from collections import deque
stack = deque()
stack.append(10)
stack.append(20)
stack.append(30)
print(stack.pop())
deque is a good choice when working with large or performance-heavy data.
You can create a simple class to manage stack operations in a cleaner way.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.items:
return None
return self.items.pop()
def peek(self):
if not self.items:
return None
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
This structure is helpful when building larger applications where stacks are a core part of the logic.
Stacks appear in many everyday programming tasks:
Each change you make is stored in a stack. When you undo, the editor pops the last action.
Each visited page is pushed to a stack. Pressing back pops the last page.
Every function call is stored in a call stack. When a function ends, Python pops it.
Stacks help evaluate arithmetic expressions and manage operator order.
Stacks help validate brackets in code editors and compilers.
These examples show why stacks are one of the most essential data structures.
You can reverse a string using a stack.
text = "hello"
stack = []
for ch in text:
stack.append(ch)
rev = ""
while stack:
rev += stack.pop()
print(rev)
This matches how many systems handle reverse operations internally.
A common use of stacks is checking if brackets match correctly.
def is_balanced(expr):
stack = []
for ch in expr:
if ch in "({[":
stack.append(ch)
elif ch in ")}]":
if not stack:
return False
stack.pop()
return not stack
This logic appears in compilers, text editors and linters.
stack = []
stack.append(10)
item = stack.pop()
top = stack[-1]
len(stack) == 0
result = []
while stack:
result.append(stack.pop())
from collections import deque
stack = deque()
for i in range(5):
stack.append(i)
s = Stack()
s.push(50)
if stack:
stack.pop()
A stack is a simple but powerful structure based on the LIFO rule. You learned how stacks work, how to push and pop values, how to peek at the top and how to handle empty conditions. You also explored deque for performance, created a custom stack class and saw real-life uses like undo actions, browser history, function calls and expression checking. Stacks form the foundation for more complex structures like queues, linked lists, trees and even recursion. Once you understand stacks, you will find many places where they fit naturally into your Python work.
Q1. Write a Python program to create an empty stack and add three items to it.
Q2. Write a Python program to remove the last added item using pop().
Q3. Write a Python program to check the top item in the stack without removing it.
Q4. Write a Python program to print all items in a stack using a loop.
Q5. Write a Python program to use collections.deque to push and pop names.
Q6. Write a Python program to count the number of items in a stack using len().
Q7. Write a Python program to create a stack and remove all items one by one using a loop.
Q8. Write a Python program to use a stack to reverse a string.
Q9. Write a Python program to check if the stack is empty and print a message accordingly.
Q10. Write a Python program to push and pop elements in numeric order and display the stack content at each step.