1. What is a Nested Loop?
A nested loop means a loop inside another loop.
The outer loop runs first.
For each iteration of the outer loop, the inner loop runs completely.
They are commonly used for patterns, tables, and 2D data (like lists or matrices).
Syntax of Nested for Loop
for outer_variable in outer_iterable:
# code of outer loop
for inner_variable in inner_iterable:
# code of inner loop
# this runs completely for each iteration of outer loop
Syntax of Nested while Loop
while condition1: # outer loop
# code block of outer loop
while condition2: # inner loop
# code block of inner loop
# usually update inner loop variable
# update outer loop variable
2. Nested for Loop
✅ Example 1: Printing Number Pairs
for i in range(3): # outer loop → 0,1,2
for j in range(2): # inner loop → 0,1
print(i, j)
Output:
0 0
0 1
1 0
1 1
2 0
2 1
3. Nested while Loop
✅ Example 1: Printing Number Pairs
i = 0
while i < 3: # outer loop
j = 0
while j < 2: # inner loop
print(i, j)
j += 1
i += 1
Output:
0 0
0 1
1 0
1 1
2 0
2 1
xample 2: Items from Two Lists
colors = ["Red", "Blue"]
fruits = ["Apple", "Banana"]
for c in colors: # outer loop
for f in fruits: # inner loop
print(c, f)
Output:
Red Apple
Red Banana
Blue Apple
Blue Banana
Code: Nested while Loop
colors = ["Red", "Blue"]
fruits = ["Apple", "Banana"]
i = 0
while i < len(colors): # outer loop
j = 0
while j < len(fruits): # inner loop
print(colors[i], fruits[j])
j += 1
i += 1
🔄 Execution Flow
Outer loop → i = 0 → "Red"
o Inner loop → j = 0,1 → "Apple", "Banana"
Outer loop → i = 1 → "Blue"
o Inner loop → j = 0,1 → "Apple", "Banana"
✅ Output
Red Apple
Red Banana
Blue Apple
Blue Banana