Web Analytics

Nested Loops

Beginner ~20 min read

A nested loop is a loop inside another loop. The inner loop executes completely for each iteration of the outer loop. Think of it like a clock: for every hour that passes, the minute hand goes around 60 times!

How Nested Loops Work

In a nested loop, the inner loop runs its full course for each single iteration of the outer loop. This creates a multiplicative effect on the total number of iterations.

Output
Click Run to execute your code
Iteration Count: If the outer loop runs m times and the inner loop runs n times, the code inside the inner loop runs m Ɨ n times total. A 10Ɨ10 nested loop runs 100 times; a 100Ɨ100 runs 10,000 times!

Working with 2D Data

Nested loops are essential for working with 2D data structures like matrices, grids, and tables. The outer loop handles rows, the inner loop handles columns.

Output
Click Run to execute your code
Pro Tip: When searching in 2D data, you need to break out of BOTH loops when you find what you're looking for. Use a flag variable or put the nested loop in a function and use return.

Pattern Printing

Nested loops are the classic way to print patterns - triangles, pyramids, rectangles, and more. The outer loop controls rows, the inner loop controls what's printed in each row.

Output
Click Run to execute your code

Practical Examples

Nested loops are used for combinations, comparisons, grid-based applications, and processing hierarchical data.

Output
Click Run to execute your code
Performance Warning: Nested loops can be slow for large data! O(n²) complexity means doubling the data quadruples the time. For 1000 items, a nested loop runs 1,000,000 times. Consider using built-in functions, list comprehensions, or libraries like NumPy for better performance.

Common Mistakes

1. Wrong variable in inner loop

# Wrong - using outer variable i in inner loop!
for i in range(3):
    for j in range(3):
        print(i)  # Should be j or both

# Correct
for i in range(3):
    for j in range(3):
        print(f"({i}, {j})")

2. Break only exits inner loop

# Wrong assumption - break exits both loops
for i in range(5):
    for j in range(5):
        if found:
            break  # Only exits inner loop!
    # Outer loop continues!

# Correct - use flag
found = False
for i in range(5):
    for j in range(5):
        if condition:
            found = True
            break
    if found:
        break

3. Modifying list while iterating

# Wrong - modifying during iteration
for row in matrix:
    for i, val in enumerate(row):
        if val == 0:
            row.remove(val)  # Dangerous!

# Correct - build new structure
new_matrix = []
for row in matrix:
    new_row = [val for val in row if val != 0]
    new_matrix.append(new_row)

4. Off-by-one in indices

# Wrong - accessing out of bounds
for i in range(len(matrix)):
    for j in range(len(matrix)):  # Wrong if not square!
        print(matrix[i][j])

# Correct - use actual row length
for i in range(len(matrix)):
    for j in range(len(matrix[i])):  # Each row's length
        print(matrix[i][j])

Exercise: Triangle Pattern

Task: Print a right triangle pattern using nested loops.

Requirements:

  • Print 5 rows
  • Row 1: 1 star, Row 2: 2 stars, ... Row 5: 5 stars
Output
Click Run to execute your code
Show Solution
rows = 5

for i in range(1, rows + 1):    # 1 to 5
    for j in range(i):          # 0 to i-1 (prints i stars)
        print("*", end="")
    print()  # New line after each row

# Output:
# *
# **
# ***
# ****
# *****

Summary

  • Nested loop: Loop inside another loop
  • Iterations: Inner loop runs completely for each outer iteration
  • Total runs: outer_iterations Ɨ inner_iterations
  • 2D data: Outer loop = rows, inner loop = columns
  • break: Only exits the innermost loop
  • Performance: O(n²) - can be slow for large data

What's Next?

Congratulations on completing the Control Flow module! You now have full control over program flow with conditionals and loops. Next, we'll dive into Lists - Python's most versatile data structure for storing collections of items!