`else` on loops
A for or while loop may have an else clause. The else block runs when the loop finishes normally, and is skipped if the loop left through break.
Detailed Explanation
The word else next to a loop looks like a mistake the first time you see it. People expect else to mean "the collection was empty". That is not the rule. The else is tied to break, not to emptiness.
Python's loop-else answers one question: did we leave because we found something, or because we ran out of items? A search is the canonical case. You walk a list looking for a record. If you find it you break. If you never find it, you need a fallback. Without else you introduce a found = False flag, set it inside the loop, and test it afterwards. With else the flag disappears. The else block is the "not found" path.
The same rule applies to while. while condition: ... else: ... runs the else when the condition becomes false. A break inside the while skips it. A return or an exception also skips it, because those leave the loop without finishing.
An empty iterable finishes immediately, so its else runs. That is the opposite of the intuition "else means the list was empty, wait, no, else means there were items". Empty means "we never broke", which means else runs. If you wanted "run only when there were items", test the collection first.
continue does not skip the else. continue is "go to the next iteration", not "leave the loop". Only break (and non-local exits) suppress else.
Because the feature is uncommon, many style guides avoid it in shared code. That is a readability choice, not a correctness one. If you use it, keep the else adjacent to a break the reader can see. A loop-else ten lines below a buried break is why the feature has a bad reputation.
try also has else, and it means something related: the else on try runs when no exception was raised. In both cases else means "the main path completed without the early exit this construct cares about".
Code Examples
# Search without a flag variable.
hosts = ["db-1", "db-2", "cache-1"]
for host in hosts:
if host.startswith("cache"):
print(f"using {host}")
break
else:
print("no cache host") # skipped, because we broke# Empty iterable: no break, so else runs.
for host in []:
print(host)
break
else:
print("nothing to scan") # nothing to scan# while-else: else runs when the condition fails, not after break.
tries = 0
while tries < 3:
tries += 1
if tries == 5: # never happens
break
else:
print("exhausted retries") # exhausted retriesCommon Gotchas
`else` is not "the loop never ran"
an empty list still runs `else`, because there was no `break`. Test emptiness separately if that is the question.
Readers miss loop-`else`
if the `break` is hidden, the `else` looks like a syntax error or an `if` leftover. Prefer a flag or a helper function when the loop body is long.
`continue` does not cancel `else`
only `break`, `return`, and exceptions skip it.
`else` after `for`/`if` is indent-sensitive
attach it to the wrong block and you change the meaning without a syntax error.