🔲 What is a Nested Loop in Python?
A nested loop is a loop inside another loop. The inner loop finishes its complete execution for every single iteration of the outer loop. They are essential for traversing 2D arrays, matrices, coordinate mapping, and complex business logic tables.
1. Basic Nested For Loop Syntax
A simple demonstration showing how the inner loop cycles completely through its range for each outer loop count.
Python
for i in range(1, 3): # Outer loop
for j in range(1, 4): # Inner loop
print(f"Outer: {i}, Inner: {j}")
Output:
Outer: 1, Inner: 1
Outer: 1, Inner: 2
Outer: 1, Inner: 3
Outer: 2, Inner: 1
Outer: 2, Inner: 2
Outer: 2, Inner: 3
Real-Time Example 1: Movie Theater Seating Grid Mapping
Generate and label all seat numbers in a cinema hall layout organized by rows and seat numbers.
Python
rows = ['A', 'B', 'C']
seat_numbers = range(1, 4)
print("Theater Seating Layout:")
for row in rows:
for seat in seat_numbers:
print(f"Seat Tag: {row}{seat}")
Output:
Theater Seating Layout:
Seat Tag: A1
Seat Tag: A2
Seat Tag: A3
Seat Tag: B1
Seat Tag: B2
Seat Tag: B3
Seat Tag: C1
Seat Tag: C2
Seat Tag: C3
Real-Time Example 2: Multiplication Matrix Generator (Billing/Pricing)
Generate a multiplication lookup table used for bulk pricing computations.
Python
print("Multiplication Table Grid (1 to 3):")
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}", end="\t")
print() # New line after inner loop completes
Output:
Multiplication Table Grid (1 to 3):
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
Real-Time Example 3: Warehouse Inventory Bin Location Mapping
Traverse stock room rack zones and shelf tiers to audit inventory location tags.
Python
zones = ["Zone-North", "Zone-South"]
shelfs = ["Shelf-1", "Shelf-2"]
for zone in zones:
for shelf in shelfs:
print(f"Scanning storage location -> {zone} : {shelf}")
Output:
Scanning storage location -> Zone-North : Shelf-1
Scanning storage location -> Zone-North : Shelf-2
Scanning storage location -> Zone-South : Shelf-1
Scanning storage location -> Zone-South : Shelf-2
Real-Time Example 4: Restaurant Menu Combination Builder
Generate all possible combo meal options pairing main courses with beverages.
Python
mains = ["Burger", "Pizza"]
drinks = ["Cola", "Lemonade", "Iced Tea"]
print("Available Meal Combos:")
for main in mains:
for drink in drinks:
print(f"Combo: {main} + {drink}")
Output:
Available Meal Combos:
Combo: Burger + Cola
Combo: Burger + Lemonade
Combo: Burger + Iced Tea
Combo: Pizza + Cola
Combo: Pizza + Lemonade
Combo: Pizza + Iced Tea
Real-Time Example 5: 2D Matrix Grid Summation (Sales Analytics)
Calculate total annual revenue by summing up values inside a 2D quarterly sales matrix.
Python
# Quarterly branch sales data (Branch 1, Branch 2)
sales_matrix = [
[12000, 15000, 13000],
[18000, 16000, 19000]
]
total_revenue = 0
for branch in sales_matrix:
for quarter_sales in branch:
total_revenue += quarter_sales
print("Total Corporate Revenue across all branches: ₹", total_revenue)
Output:
Total Corporate Revenue across all branches: ₹ 93000
Real-Time Example 6: School Exam Schedule Slotting
Pair exam subjects with available morning and evening time slots.
Python
subjects = ["Maths", "Science"]
time_slots = ["Morning Shift", "Evening Shift"]
print("Exam Schedule Allocations:")
for sub in subjects:
for slot in time_slots:
print(f"Exam: {sub} scheduled in {slot}")
Output:
Exam Schedule Allocations:
Exam: Maths scheduled in Morning Shift
Exam: Maths scheduled in Evening Shift
Exam: Science scheduled in Morning Shift
Exam: Science scheduled in Evening Shift
Real-Time Example 7: Pattern Printing (Star Triangle UI Design)
Use nested loops to construct geometric patterns for console UI decoration.
Python
print("Star Pyramid Pattern:")
for i in range(1, 5):
for j in range(i):
print("*", end=" ")
print()
Output:
Star Pyramid Pattern:
*
* *
* * *
* * * *
Real-Time Example 8: E-Commerce Variant SKU Generator
Generate unique Stock Keeping Unit (SKU) combinations for products available in multiple sizes and colors.
Python
product_name = "T-Shirt"
sizes = ["S", "M", "L"]
colors = ["Red", "Blue"]
print("Generated Product Variants:")
for size in sizes:
for color in colors:
print(f"SKU Code: {product_name}-{size}-{color}")
Output:
Generated Product Variants:
SKU Code: T-Shirt-S-Red
SKU Code: T-Shirt-S-Blue
SKU Code: T-Shirt-M-Red
SKU Code: T-Shirt-M-Blue
SKU Code: T-Shirt-L-Red
SKU Code: T-Shirt-L-Blue
Real-Time Example 9: Finding Duplicate Items in Two Lists
Compare two distinct inventory lists using nested loops to locate matching catalog items.
Python
store_a_items = ["Laptop", "Mouse", "Keyboard"]
store_b_items = ["Monitor", "Mouse", "Keyboard"]
print("Common Items Found in Both Stores:")
for item_a in store_a_items:
for item_b in store_b_items:
if item_a == item_b:
print(f"- Match: {item_a}")
Output:
Common Items Found in Both Stores:
- Match: Mouse
- Match: Keyboard
Real-Time Example 10: Nested Loop with Break Statement
Break out of the inner loop early when a specific threshold condition is met.
Python
for week in range(1, 3):
print(f"--- Week {week} ---")
for day in range(1, 8):
if day > 3:
print(" Mid-week rest triggered. Breaking inner day loop.")
break
print(f" Processing Day {day}")
Output:
--- Week 1 ---
Processing Day 1
Processing Day 2
Processing Day 3
Mid-week rest triggered. Breaking inner day loop.
--- Week 2 ---
Processing Day 1
Processing Day 2
Processing Day 3
Mid-week rest triggered. Breaking inner day loop.
Summary of Nested Loops
- Definition: A loop placed inside the body of another loop.
- Execution Rule: The inner loop executes completely for every single iteration of the outer loop.
- Applications: Perfect for matrix manipulation, coordinate systems, grid layouts, product variants, and multi-dimensional reports.