Python Nested Loops
Nested loops are loops inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.
They are commonly used to work with multi-dimensional data structures like matrices, tables, or grids.
Syntax
for outer_var in outer_sequence:
for inner_var in inner_sequence:
# inner loop block
# outer loop blockYou can nest any kind of loop — for inside for, while inside for, etc.
Example 1: Nested for Loop
for i in range(1, 4): # Outer loop
for j in range(1, 3): # Inner loop
print(f"i={i}, j={j}")Output:
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2Example 2: Printing a Pattern
rows = 4
for i in range(1, rows + 1):
for j in range(1, i + 1):
print("*", end="")
print()Output:
*
**
***
****Example 3: Nested while Loop
i = 1
while i <= 3:
j = 1
while j <= 2:
print(f"i={i}, j={j}")
j += 1
i += 1Output:
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2Example 4: Looping Through a Matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for item in row:
print(item, end=" ")
print()Output:
1 2 3
4 5 6
7 8 9 Things to Keep in Mind
- Nested loops are slower for large datasets.
- Complexity increases with each nested level:
O(n)→O(n²)→O(n³)…
Common Use Case: Multiplication Table
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25 Summary Table
| Nested Type | Description |
|---|---|
for inside for | Most common nested loop |
while inside for | Used when inner logic needs condition |
for inside while | Useful for grouped iteration |
while inside while | Rare, but possible |
Exercise
Task: Print a triangle pattern using nested for loops.
1
12
123
1234for i in range(1, 5):
for j in range(1, i + 1):
print(j, end="")
print()