Sub topic 12
The Loop else Clause
This chapter assumes you can write for and while loops, use break and continue, and read if/else blocks. It also assumes you know range() and enumerate() from earlier chapters. Here you learn what else means when it is attached to a loop, when it is useful, and where it misleads readers.
What else means on a loop
A for loop (and a while loop) can have an else block after its body. The block runs when the loop ends normally, meaning it ran out of items or its condition became false. It is skipped if the loop was left through break.
Read it as "no break". The usual name for the clause is a poor guide to its behavior, because it does not mean "otherwise, if the loop did not run".
for n in range(2, 10):
for d in range(2, n):
if n % d == 0:
break
else:
print(n, "is prime")This prints 2 is prime, 3 is prime, 5 is prime, and 7 is prime. For each n, the inner loop tries divisors from 2 up to n - 1. If one divides evenly, break leaves the inner loop and its else is skipped. If no divisor is found, the inner loop ends normally and the else reports a prime.
For n = 2, range(2, 2) is empty. The loop body never runs, the loop still ends normally, and the else runs. This is correct, because 2 has no divisors to rule it out.
The control flow
The diagram shows the only two exits from a loop that has an else. The first is exhaustion, where the else runs. The second is break, where it does not.
The search pattern
The clause is most useful for "search, and handle the not-found case". break marks "found", and else marks "not found".
def report_first_negative(values):
for i, v in enumerate(values):
if v < 0:
print(f"negative at index {i}")
break
else:
print("no negatives")
report_first_negative([3, 8, -2, 5])
report_first_negative([3, 8, 5])The output is negative at index 2, then no negatives.
Without else, you need a flag variable:
def report_first_negative_flag(values):
found = False
for i, v in enumerate(values):
if v < 0:
print(f"negative at index {i}")
found = True
break
if not found:
print("no negatives")Both versions behave the same. The else version removes one variable and one condition that you could forget to update.
What counts as a normal finish
Only break suppresses the else. Several other things look like they might, but do not.
| How the loop ends | Does `else` run? |
|---|---|
| Iterable exhausted | Yes |
| Iterable is empty | Yes |
| `while` condition becomes false | Yes |
| `break` | No |
| `return` inside a function | No, because the whole function is left |
| An exception propagates out | No, because control leaves the loop |
| `continue` on some iterations | Yes, if the loop is not otherwise broken |
The continue case surprises people:
for n in [1, 2, 3]:
if n == 2:
continue
print(n)
else:
print("finished")This prints 1, 3, and finished. continue only skips the rest of one iteration. The loop still runs to the end.
else on while loops
while loops accept the same clause. It runs when the condition becomes false, and it is skipped on break.
value = 3
count = 0
while count < 4:
value *= 2
count += 1
if value > 100:
print("exceeded 100")
break
else:
print("limit not reached", value)Starting from 3, four doublings reach 48, which never passes 100. The loop ends because count < 4 became false, so the output is limit not reached 48.
A while loop whose condition is false on the first check also runs its else, in the same way an empty for loop does.
Breaking out of nested loops
A break leaves only the innermost loop. The else clause gives you a way to turn an inner break into an outer one:
grid = [[1, 2], [3, 4], [5, 6]]
target = 4
for r, row in enumerate(grid):
for c, cell in enumerate(row):
if cell == target:
break
else:
continue
print("found at", r, c)
break
else:
print("not found")This prints found at 1 1. Trace it step by step:
- For row 0, the inner loop finds nothing and ends normally. Its
elserunscontinue, which moves to the next row. - For row 1, the inner loop finds 4 and breaks. Its
elseis skipped. - Control reaches the
printand then the outerbreak. The outerelseis skipped too.
If target were 9, every inner else would run continue, the outer loop would finish normally, and not found would print.
This idiom works, but many readers find it hard to follow. A helper function that uses return is often clearer:
def find(grid, target):
for r, row in enumerate(grid):
for c, cell in enumerate(row):
if cell == target:
return r, c
return None
print(find([[1, 2], [3, 4], [5, 6]], 4)) # (1, 1)
print(find([[1, 2], [3, 4], [5, 6]], 9)) # NoneCommon mistakes
Wrong indentation
The else binds to whichever statement it lines up with. If you indent it under the if, it becomes an ordinary if/else and runs on each iteration:
for n in [1, 3, 5]:
if n % 2 == 0:
print("even found")
break
else:
print(n, "is odd")This prints 1 is odd, 3 is odd, and 5 is odd. No break ever happens here, but the else runs for a different reason. It belongs to the if, not the loop. When you mean the loop's else, check that it is at the same indentation as for or while.
Expecting else when the loop never ran
Some people read the clause as "else, if the loop body did not execute". That is wrong. An empty iterable runs the else, as the n = 2 prime case showed. If you need to detect an empty input, test it before the loop, for example with if not items:.
Using the clause for everything
If a loop has no break, an else block is the same as code placed right after the loop. It adds nothing and confuses readers.
Alternatives to consider
The else clause is not always the clearest tool. For simple searches, Python has built-ins that say what they mean:
values = [4, 7, 9]
has_negative = any(v < 0 for v in values)
first_odd = next((v for v in values if v % 2), None)
print(has_negative) # False
print(first_odd) # 7any() answers "does one exist?" and next() with a default returns the first match or None. Use a loop with else when the loop body does more than test a condition, such as printing, accumulating, or running several steps before deciding.
Choose between the options like this:
- Use
any()ornext()when you only need a yes/no answer or the first match. - Use
for/elsewhen the "found" and "not found" paths both need real statements. - Use a function with
returnwhen you must leave several loops at once. - Add a short comment such as
# no breakabove theelse, because many readers will not recognize the construct at a glance.
Exercises
Exercise
What does this code print? for n in [2, 4, 6]: if n % 2 == 1: break else: print("all even")
Show answer
It prints "all even". No element is odd, so break never runs, the loop ends normally, and the else block executes.
Exercise
Write a loop with an else clause that checks whether the list words contains a string of length 10 or more. Print "long word: <word>" for the first match and "no long words" otherwise.
Show answer
for w in words: if len(w) >= 10: print("long word:", w) break else: print("no long words")
Exercise
A learner writes while False: pass followed by else: print("done") at the same indentation as while. Does "done" print? Explain.
Show answer
Yes. The condition is false on the first check, so the loop ends normally without a break, and the else block runs. A while loop whose condition starts false behaves like an empty for loop.