Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Nested Loops
Nested loops are loops inside loops. The inner loop runs completely for each iteration of the outer loop. They're useful for working with 2D data like matrices, grids, and tables.
Nested Loops
# Basic nested loop - multiplication table
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 each row
# Pattern - right triangle
print("\nTriangle:")
for i in range(1, 6):
print("* " * i)
# 2D list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("\nMatrix:")
for row in matrix:
for item in row:
print(f"{item:3}", end=" ")
print()
# Finding pairs
print("\nPairs that sum to 10:")
numbers = [1, 3, 5, 7, 9]
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == 10:
print(f" {numbers[i]} + {numbers[j]} = 10")Tip
Tip
Nested loops multiply iterations: 100×100 = 10,000. For large data, consider comprehensions, set operations, or algorithms that avoid nesting.
for loops for known counts, while loops until a condition is met
Common Mistake
Warning
Using the same variable name in nested loops (for i... for i...) overwrites the outer variable. Always use different names: i, j, k.
Practice Task
Note
(1) Print a 5x5 star rectangle. (2) Print a right triangle with *. (3) Print a multiplication table 1-10. (4) Flatten a 2D list.