Why does python use 'else' after for and while loops?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python's loop else looks strange if you expect else to mean "the opposite branch of if." In loops, it means something different: run this block only if the loop finished normally without hitting break. Once you view it as a "no break occurred" clause, the feature becomes much easier to read.
What Loop else Actually Means
A for or while loop can have an else block. That block runs only when the loop ends naturally.
Natural completion means:
- a
forloop exhausted its iterable - a
whileloop condition became false - no
breakstatement interrupted the loop
This prints no odd numbers found because the loop never hit break.
Now compare it with a case that does break:
This prints found odd, and the else block is skipped.
Why Python Has This Feature
Loop else is mainly a control-flow convenience for search-style logic. It lets you write:
- loop through candidates
- stop early if you find what you want
- run a fallback block only if you never found it
Without loop else, many people write an extra flag variable:
That works, but the flag exists only to remember whether break happened. Loop else expresses that idea directly.
A Classic Example: Prime Checking
One of the clearest uses is trial division when checking if a number is prime.
The else block means, "we checked all possible divisors and never broke out by finding one."
You could also write this function with an immediate return True after the loop, but the loop else makes the connection to "no factor was found" explicit.
while Loops Use the Same Rule
The behavior is identical for while loops.
This prints the numbers and then the else block because the loop ended when the condition became false.
If a break occurs, the else block is skipped:
What Does Not Skip else
The loop else is specifically about break. It is not suppressed by every possible control-flow event inside the loop body.
For example:
- '
continuedoes not stop theelse' - exhausting the iterable still triggers the
else
This still runs the else block.
If the loop exits because of return or an uncaught exception, the else block also does not run, but that is because execution leaves the whole function or propagates the error.
When It Helps Readability
Loop else is most helpful when the loop body is clearly a search for something that may or may not be found. Examples include:
- finding a matching item
- checking for a failure condition
- validating that no forbidden case exists
It is less helpful when there is no obvious search or break condition. In those cases, readers may have to pause and re-parse the loop to remember what the else means.
That is why some Python developers like the feature and some avoid it. The feature is valid, but it should earn its keep by making the control flow clearer.
Common Pitfalls
- Reading loop
elseas if it were paired with theifinside the loop. It is paired with the loop itself. - Forgetting that
elseruns when the loop completes withoutbreak, even if the loop body executed many times. - Using loop
elsein code that is not really a search or no-break scenario. That can make the code harder to scan. - Expecting
continueto suppress theelse. It does not. - Replacing a simple post-loop statement with loop
elseeven when thebreaklogic is absent. That adds complexity without benefit.
Summary
- Loop
elsein Python means "run this block if the loop ended withoutbreak." - It works the same way for both
forandwhile. - It is especially useful for search-style loops and validation checks.
- '
continuedoes not skip theelse;breakdoes.' - Use it when it clarifies control flow, not just because the syntax exists.
Related reading
- Why does Python's hash of infinity have the digits of π?
- Why does Python's is operator behave unexpectedly with integers?
- Why does Python's itertools.permutations contain duplicates? When the original list has duplicates
- Why does rangestart, end not include end?
- Why does return list.sort return None, not the list?
- Why does running a python file inside a pod not have the same behavior as running it directly?
- Why does the standardization differ between Python's 'StandardScaler' and Matlab's 'zscore'?
- Why does this code for initializing a list of lists apparently link the lists together?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.