Sub topic 9
break and continue in nested loops
What this chapter assumes
You should already know how a single while loop works: the condition is checked before each pass, and the body must change some state so the condition eventually becomes false. You should also know what break and continue do in one loop, and how the loop else clause works. This chapter covers what changes when one loop sits inside another.
Two ideas carry most of the chapter:
breakandcontinuealways act on the innermost loop that contains them.- Python has no statement for "leave two loops" or "continue the outer loop". You have to build that behavior from other tools.
Which loop does a statement affect?
When Python runs break, it looks outward from the statement for the nearest enclosing while or for. It stops that loop and carries on with the code after it. Any outer loop keeps running.
i = 0
while i < 3:
j = 0
while j < 3:
if j == 2:
break
print(i, j)
j += 1
print("inner loop ended, i =", i)
i += 1This prints:
0 0
0 1
inner loop ended, i = 0
1 0
1 1
inner loop ended, i = 1
2 0
2 1
inner loop ended, i = 2The break fires when j reaches 2. It ends only the inner loop. The print("inner loop ended...") line runs, i increases, and the outer condition is checked again. The if statement is not a loop, so break skips past it and applies to the while around it.
The diagram shows why the code after the inner loop always runs, whether the inner loop ended by break or because its condition became false. That code is the natural place to update outer state.
Leaving both loops
Sometimes the inner break should end the whole search. You have four common options.
| Technique | Best when | Cost |
|---|---|---|
| `return` from a function | The loops are the core of a function | Needs a function |
| Flag variable | You must stay in the current scope | Extra state to keep correct |
| Inner `else` with `continue`, then `break` | You want no extra variable | Hard to read at first |
| Raise and catch an exception | Loops are deeply nested or span several calls | Heavier, unusual for ordinary control flow |
Option 1: return from a function
This is usually the cleanest choice. Wrap the loops in a function and return as soon as you have the answer. return ends every loop in the function at once.
def find_pair(nums, target):
i = 0
while i < len(nums):
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
return i, j
j += 1
i += 1
return None
print(find_pair([2, 7, 11, 15], 9))This prints (0, 1). If no pair adds up to the target, the function falls through to return None. Returning a value also means the caller does not need to inspect leftover loop variables.
Option 2: a flag variable
A flag is a variable that records "the inner loop found something". The outer condition tests it, so the outer loop stops after the inner loop breaks.
nums = [2, 7, 11, 15]
target = 9
found = None
i = 0
while i < len(nums) and found is None:
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
found = (i, j)
break
j += 1
i += 1
print(found)This prints (0, 1). The inner break ends the inner loop. The outer loop then runs i += 1 and rechecks its condition. Because found is no longer None, the outer loop ends.
Note that i was incremented once after the match. If you need the index of the row where the match happened, store it in found (as this code does) instead of reading i afterward.
Option 3: else on the inner loop
Recall that a loop's else block runs only if the loop ended without break. Applied to the inner loop, that means "the inner loop found nothing". In that case you move on to the next outer pass with continue. If the inner loop did break, the else block is skipped and the statement right after the inner loop runs, which is a break for the outer loop.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
r = 0
while r < len(grid):
c = 0
while c < len(grid[r]):
if grid[r][c] == target:
break
c += 1
else:
r += 1
continue
break
if r < len(grid):
print("found at", (r, c))
else:
print("not found")This prints found at (1, 1). Trace it for row 0: the inner loop runs out of columns, so its else block runs. That block increments r and continues the outer loop. For row 1, the inner loop breaks at c == 1. The else block is skipped, so Python reaches the bare break at the outer level and leaves the outer loop with r and c still pointing at the match.
The increment of r sits inside the else block because continue would otherwise skip it. That detail leads into the next section.
Option 4: exceptions
You can define an exception class, raise it inside the inner loop, and catch it outside both loops. This works for any nesting depth. It is rarely needed with two loops, and it hides the loop exit inside exception handling. Reserve it for cases where the exit has to cross several function calls.
continue in nested loops
continue also acts on the innermost loop. It jumps to that loop's condition check, skipping the rest of that loop's body only.
i = 0
while i < 3:
i += 1
j = 0
while j < 3:
j += 1
if j == i:
continue
print(i, j)This prints every pair where i and j differ:
1 2
1 3
2 1
2 3
3 1
3 2Both updates (i += 1 and j += 1) come before any continue, so each loop still advances. If the j += 1 line were at the bottom of the inner body, the first time j == i the inner loop would repeat forever with the same j.
Continuing the outer loop from the inner loop
Python has no continue outer. The usual substitute is to let the inner loop break after setting a flag, and then continue at the outer level.
rows = [[1, 2, 3], [4, -5, 6], [7, 8, 9]]
total = 0
r = 0
while r < len(rows):
row = rows[r]
r += 1
c = 0
bad = False
while c < len(row):
if row[c] < 0:
bad = True
break
c += 1
if bad:
continue
total += sum(row)
print(total)This prints 30. The row [4, -5, 6] contains a negative number, so it is skipped. The sum is 6 + 24. Note the order of operations: r += 1 runs near the top of the outer body, before the inner loop and before the outer continue. That keeps the outer loop moving no matter which path the body takes.
Moving the inner scan into a small helper function makes this clearer, because the helper can use return:
def has_negative(row):
c = 0
while c < len(row):
if row[c] < 0:
return True
c += 1
return False
rows = [[1, 2, 3], [4, -5, 6], [7, 8, 9]]
total = 0
r = 0
while r < len(rows):
row = rows[r]
r += 1
if has_negative(row):
continue
total += sum(row)
print(total)The output is again 30. The outer loop now reads as plain logic, and the nested-loop mechanics are hidden inside a function with a name.
Resetting inner state
Every time the outer loop starts a new pass, the inner loop needs its own variable set back to its starting value. Forgetting this is the most common nested-loop bug.
i = 0
j = 0 # bug: j is set only once
while i < 3:
while j < 3:
print(i, j)
j += 1
i += 1This prints only 0 0, 0 1, 0 2. After the first pass j is 3, so the inner condition is false at the start of every later pass, and the inner loop never runs again. The fix is to assign j = 0 inside the outer body, before the inner loop, as in the earlier examples.
Other mistakes to look for
- Expecting
breakto stop everything. If code after an inner loop assumes the search is over, check what happened inside. Use a flag orreturnto carry the result outward. - Skipping an outer update with
continue. An outer-levelcontinuejumps over everything below it in the outer body, includingr += 1if you placed it at the bottom. Put the update before thecontinue, or at the top of the body. - Reading loop variables after a loop that never ran. If the outer loop's condition is false from the start, variables like
cin the grid example were never assigned. The checkr < len(grid)in the grid code avoids touchingcin that case. - Wrong
elseplacement. Anelseindented to match the innerwhilebelongs to the inner loop. Anelseindented to match the outerwhilebelongs to the outer loop. Indentation decides which one you wrote. - Using nested loops where one is enough. If you only need to search a flat collection, a single loop with
breakis simpler. Nesting adds the need for resets, flags and careful updates.
Choosing a structure
Start from what the code must do when the inner loop finds its answer.
- If the answer ends the entire job and the loops live in a function, use
return. - If the code must stay in the current scope, use a flag and test it in the outer condition.
- If the inner loop's result only decides whether to skip one outer pass, set a flag and use an outer
continue, or move the inner scan into a helper. - If you want a compact form and your readers know the idiom, use the inner
elsepattern.
Also consider whether for loops fit better. When you iterate over known sequences, for handles the variable updates and resets for you, which removes several of the mistakes above. The same break, continue, and else rules apply to for loops, so everything in this chapter carries over.
Exercise
In the code below, how many times does the line print(i, j) run, and what is the final value of i? i = 0 while i < 3: i += 1 j = 0 while j < 3: j += 1 if j == 2: break print(i, j)
Show answer
It runs 3 times, and the final value of i is 3. On each outer pass the inner loop prints once, when j is 1, then j becomes 2 and break ends the inner loop before the print. The outer loop runs for i = 1, 2, 3, so the output is "1 1", "2 1", "3 1".
Exercise
Write a function firstnegativerow(rows) that takes a list of lists of numbers and returns the index of the first row that contains a negative number, or -1 if no row does. Use nested while loops. What does firstnegativerow([[1, 2], [3, -4], [-5]]) return?
Show answer
One solution: def firstnegativerow(rows): r = 0 while r < len(rows): c = 0 while c < len(rows[r]): if rows[r][c] < 0: return r c += 1 r += 1 return -1 The call returns 1. The return statement leaves both loops at once, so no flag is needed. The inner variable c is reset to 0 on every outer pass, and r is incremented only after the inner loop finishes without a match.
Exercise
Why does the following code print nothing after the first outer pass, and how do you fix it? i = 0 j = 0 while i < 2: while j < 2: print(i, j) j += 1 i += 1
Show answer
It prints "0 0" and "0 1" and then nothing more for i = 1, because j stays at 2 and the inner condition is false. The fix is to move j = 0 inside the outer loop, just before the inner while, so the inner variable is reset on every outer pass. It will then print four lines: 0 0, 0 1, 1 0, 1 1.