๐งฑ Python Nested Loops โ Loops Inside Loops
Introduction ๐
A nested loop means placing one loop inside another. The inner loop runs completely **for each iteration** of the outer loop. Nested loops are commonly used in pattern printing, matrix operations, working with 2D lists, and performing repeated tasks within repeated tasks.
Note
๐ก A nested loop = Outer loop ร Inner loop executions.
1. Basic Nested For Loop ๐งฑ
basic_nested_for.py
for i in range(3): # Outer loop
for j in range(3): # Inner loop
print(i, j)โ๏ธ Output will show all pairs of (i, j).
โ๏ธ Inner loop runs fully for each outer loop iteration.
2. Nested While Loop ๐
nested_while.py
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 13. For Loop Inside a While Loop ๐
for_inside_while.py
i = 1
while i <= 3:
for j in range(1, 4):
print(i, j)
i += 14. While Loop Inside a For Loop ๐งฉ
while_inside_for.py
for i in range(1, 4):
j = 1
while j <= 3:
print(i, j)
j += 15. Pattern Printing Using Nested Loops โญ
Star Triangle
pattern_star.py
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()Number Pattern
pattern_number.py
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end=" ")
print()6. Working With 2D Lists (Matrix) ๐งฎ
2d_list.py
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()7. Nested Loops With Break ๐
nested_break.py
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)Note
โ๏ธ Break affects only the INNER loop.
8. Nested Loops With Continue ๐
nested_continue.py
for i in range(3):
for j in range(3):
if j == 1:
continue
print(i, j)9. Nested Loops With Else ๐ฏ
nested_else.py
for i in range(3):
for j in range(3):
print(i, j)
else:
print("Inner loop completed for i =", i)10. Real-World Example ๐
Searching an item in 2D list
search_2d_list.py
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
search = 50
for row in matrix:
for item in row:
if item == search:
print("Found", search)
breakMultiplication Table
multiplication_table.py
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end=" ")
print()11. Performance Consideration โ ๏ธ
Nested loops multiply work. Example: 3ร3 = 9 iterations; 100ร100 = 10,000 iterations. Use them wisely for large datasets.
Note
๐ง Try to optimize logic when deeply nested loops become slow.
Conclusion ๐
>>โNested loops unlock powerful repetitive structures โ perfect for patterns, matrices, and complex iterations.โ โจ
You now fully understand Pythonโs nested loops! Want the next topic? Try Loop Control Statements (break, continue, pass), Range(), or List Comprehensions. Just tell me! ๐