Loop Else
Python · Loops
Theory
Both for and while loops can have an else block, and it has a specific meaning: the else runs only if the loop finished normally, that is, the for loop ran out of items or the while condition became false. If the loop was stopped by break, the else is skipped. In the example, no item in [1, 2, 3] equals 5, so break never runs and 'Completed without break' is printed. With [1, 5, 3], break fires on 5 and nothing is printed.
The name confuses many people: it is best read as 'no break'. It is not related to whether the loop ran at all; a for loop over an empty list goes straight to the else. Its classic use is a search: loop over the items, break when you find a match, and put the 'not found' handling in else, which removes the need for a found = False flag variable. Keep it for that pattern; if the meaning is not obvious to readers, a flag or any() can be clearer.
Why we use it
Search code often needs to know afterwards whether the loop found something. Loop else gives that answer directly, without an extra flag variable that you set inside the loop and check afterwards.
When to use it
Use for/while ... else for 'search, and handle not-found' logic with break. If the loop has no break, the else always runs and adds nothing. For simple yes/no checks, any(x == 5 for x in items) or 5 in items is clearer.
How it works
- Start the loop
- Take the next item
- Does the item trigger break? Yes: Leave the loop and SKIP the else block. No: Keep looping.
- Items left? Yes: Take the next one. No: Loop ended normally.
- Run the else block: print('Completed without break')
- Continue after the loop
Syntax
for item in iterable:
...
else:
...Example
for n in [1,2,3]:
if n == 5:
break
else:
print("Completed without break")Key points
- Useful for "search and confirm not found" patterns
- Skipped entirely if break was executed
- Read it as 'no break', not 'if the loop did not run'
- An empty for loop goes straight to the else
- Works on both for and while loops