sec03 - Python Nested Loops Guide — Double Loops, break/continue, and Infinite Loop Prevention
スポンサーリンク

1. Basics of Nested Loops

Let’s start by reviewing the basic structure of nested loops. In Python, you can perform repeated operations within another loop by nesting for or while statements. This concept is called “loop nesting.”

In the following example, the outer and inner loops work together to generate a 3×3 table-like output.

for i in range(3):
    for j in range(3):
        print(f'(i[{i}], j[{j}])', end=' ')

    print()

Output:

(i[0], j[0]) (i[0], j[1]) (i[0], j[2]) 
(i[1], j[0]) (i[1], j[1]) (i[1], j[2])
(i[2], j[0]) (i[2], j[1]) (i[2], j[2])

The changes in i and j can be summarized in the following table:

Outer Loop { i }Inner Loop { j }
00 → 1 → 2
10 → 1 → 2
20 → 1 → 2

This means that for each iteration of the outer loop, the inner loop executes all its iterations. When the outer loop returns to its beginning and the inner loop (for j in range(3):) starts again, the range(3) sequence begins from the start (0 → 1 → 2).

Next, let’s look at an example of a nested loop using a list.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    for value in row:
        print(value, end=' ')
    print()

Output:

1 2 3
4 5 6
7 8 9

The flow of processing can be visualized in the following table:

Value of rowChanges in value
[1, 2, 3]1 → 2 → 3
[4, 5, 6]4 → 5 → 6
[7, 8, 9]7 → 8 → 9

The outer loop retrieves each row one by one, and the inner loop processes each element within that row.

Next, here’s an example of nesting using a while loop.

i = 0
while i < 3:
    j = 0
    while j < 3:
        print(i, j)
        j += 1
    i += 1

In the case of a while loop, it’s important to define a counter variable (like j for the inner loop) to prevent infinite loops.

As we’ve seen, besides nesting for within for or while within while, you can also combine for and while depending on the desired iteration behavior — for example, when mixing fixed and variable repetitions.

2. Basic Loop Control (break / continue)

In nested loops, you can control iteration using break and continue. However, it’s crucial to understand whether they affect the inner loop or the outer loop.

2.1 Behavior of break

In the following example, break is used inside the inner loop.

for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j)

Output:

0 0
1 0
2 0

Since the loop breaks when j equals 1 (and thus print(i, j) is not executed), only the cases where j equals 0 are printed. The break statement terminates only the inner loop, while the outer loop continues (i proceeds from 0 → 1 → 2).

In the next example, break is used in the outer loop.

for i in range(3):
    if i == 1:
        break
    for j in range(3):
        print(i, j)

Output:

0 0
0 1
0 2

Since the loop breaks when i equals 1, only the results where i equals 0 are printed. When a break occurs in the outer loop, the entire loop structure terminates.

2.2 Behavior of continue

The continue statement skips the current iteration of a loop.

for i in range(3):
    for j in range(3):
        if j == 1:
            continue
        print(i, j)

Output:

0 0
0 2
1 0
1 2
2 0
2 2

When continue is triggered inside the inner loop, the corresponding print(i, j) is skipped, and the loop immediately returns to the beginning of for j in range(3):. Therefore, only values of j other than 1 are printed.

The next example uses continue in the outer loop.

for i in range(3):
    if i == 1:
        continue
    for j in range(3):
        print(i, j)

Output:

0 0
0 1
0 2
2 0
2 1
2 2

When i equals 1, the continue statement causes the loop to return to the beginning of the outer loop, so only iterations where i is not 1 are printed.

スポンサーリンク

3. Variable Scope and Value Updates

In nested loops, it’s important to pay attention to variable scope. In Python, loop variables exist in the same scope (within a function or the script itself). Therefore, be careful not to accidentally overwrite other variables in the same scope or reference unintended values.

(Variable scope will be covered in a dedicated lecture.)

for i in range(2):
    for j in range(3):
        print(i, j)
print('i after loop:', i)
print('j after loop:', j)

Output:

0 0
0 1
0 2
1 0
1 1
1 2
i after loop: 1
j after loop: 2

As shown, even after the loops have finished, variables i and j still exist. To avoid referencing unintended values, always be mindful of variable scope.

4. Indentation, Readability, and Pitfalls of Deep Nesting

Nested loops introduce deeper indentation, which can reduce readability. Use blank lines and comments appropriately to clarify the structure.

You can technically nest loops three or four levels deep, but the deeper the nesting, the harder it becomes to read and maintain, increasing the likelihood of hidden bugs. If extensive iteration is required, consider breaking your logic into separate functions to prevent overly deep nesting.

(Functions will be covered in a dedicated lecture.)

for i in range(2):
    print(f'Start of i loop: {i}')
    for j in range(2):
        print(f'  Processing j: {j}')
        for k in range(3):
            if k == 2:
                continue
            print(f'    Processing k: {k}')
    print(f'End of i({i}) loop')

Output:

Start of i loop: 0
  Processing j: 0
    Processing k: 0
    Processing k: 1
  Processing j: 1
    Processing k: 0
    Processing k: 1
End of i(0) loop
Start of i loop: 1
  Processing j: 0
    Processing k: 0
    Processing k: 1
  Processing j: 1
    Processing k: 0
    Processing k: 1
End of i(1) loop

5. Infinite Loops and Exit Conditions

When nesting while loops, an incorrect exit condition can easily lead to an infinite loop.

i = 0
while i < 3:
    j = 0
    while j < 3:
        print(i, j)
        # Forgetting 'j += 1' will cause an infinite loop
    i += 1  # Don’t forget 'i += 1' either

If neither i nor j is updated, the same process will repeat forever — so always ensure that both counters are incremented properly.

スポンサーリンク