PythonConditional Statements and LoopsPython loop control

What is the `else` clause in a loop?

Question 58 of 88 · Updated

On this page

Python's optional loop else clause executes when a loop completes normally: when a for loop exhausts its iterator or a while loop's condition becomes false. A break that exits that loop skips its else suite. A return or an exception that leaves the loop also prevents normal completion.

A useful mental model is "what should happen if this loop runs to completion without an early exit?" The clause belongs to the loop itself, not to an if statement inside its body.

The preceding break and continue lessons introduced this rule. Here we examine both loop forms, nested completion, exception behavior, search algorithms and cases where a simpler alternative is preferable.

1. Basic for-else syntax#

PYTHON
for x in [2,4,6]: if x % 2: break else: print('all even') print('done')

Output:

all even
done

The loop checks each number for an odd remainder. No number satisfies the break condition, so the iterator is exhausted normally and the else suite prints all even. Execution then reaches the statement after the loop.

If an odd number were encountered, break would skip the else suite. The final print would still execute, assuming no other control transfer interrupts execution.

The else header is aligned with for. Its suite is indented below it. Aligning else with the inner if instead would create an if-else statement with different behavior.

Loading diagram…

The diagram describes normal execution paths and a break. Unhandled exceptions and returns can transfer control elsewhere; required cleanup still follows the normal language rules.

2. Practical search with for-else#

PYTHON
def find(values,target): for i,value in enumerate(values): if value==target: result=i break else: result=None return result print(find([7,8],7),find([7,8],9),find([],7))

Output:

0 None None

The function searches for the first matching value. A successful comparison assigns the index and breaks. Normal exhaustion without finding a match assigns None in the else suite.

A match at index zero is a valid result. Testing whether the returned value is None distinguishes that result from absence. A generic truth test would incorrectly treat zero as missing.

Notice that result is assigned in either ordinary completion path: successful match followed by break, or normal exhaustion followed by else. The function assumes a finite iterable when no match exists and an appropriate equality contract.

For n values, the search performs at most n comparisons. It can finish after the first comparison if the target is present at the first position. With bounded-cost comparisons and retrieval, worst-case time is O(n), and auxiliary storage is O(1) under a fixed-size index model.

3. The while-else statement#

PYTHON
def attempt(values): i=0 while i<len(values): if values[i]: print('ready',i) break i+=1 else: print('exhausted') attempt([False,True]); attempt([False,False]); attempt([])

Output:

ready 1
exhausted
exhausted

The function examines a finite indexable sequence of flags. If it finds a truthy value, it prints the position and breaks. Otherwise, its counter eventually reaches the sequence length, making the condition false.

The empty sequence also executes else. The condition is false on its first evaluation, so no body execution is needed before normal completion.

Loading diagram…

This is a demonstration of while-else over known finite data, not a production polling or retry mechanism. For an external operation, attempt limits, deadlines and per-operation timeouts may also be necessary. Those topics are introduced in the infinite-loop lesson.

4. Exactly when does loop else execute?#

How control reaches the end of a loopDoes its else suite execute?
for iterator is exhausted normallyYes
for iterable is emptyYes
while condition becomes falseYes
while condition is false initiallyYes
continue followed eventually by normal completionYes
break exits this loopNo
return leaves the enclosing function from the loop bodyNo
Unhandled exception leaves the loopNo
Loop never terminatesNot reached

The phrase "runs if there is no break" is a helpful shorthand, but it is incomplete. An exception or return can leave a loop without executing break and still bypass its else suite. The precise rule is normal completion.

For a for loop, normal exhaustion means the iteration mechanism receives its ordinary exhaustion signal. For while, the condition is successfully evaluated and found false. A failure while evaluating a condition or obtaining the next item is not normal completion merely because no break occurred.

5. Continue does not disable loop else#

PYTHON
for x in range(3): continue else: print('finished')

Output:

finished

Every iteration executes continue. Nevertheless, the range iterator eventually runs out of items, and else executes once.

The continue statement skips the remainder of an individual iteration. It does not permanently change the loop's completion state. The same principle applies to a while loop that reaches a false condition after one or more continues.

In particular, a loop else suite does not imply that useful work was performed in every iteration, or even in any iteration. It means that the loop completed through its normal termination mechanism.

6. Nested loops have independent else clauses#

PYTHON
for row in [[1,2],[3]]: for x in row: if x==2: break else: print('no 2 in',row) else: print('all rows visited')

Output:

no 2 in [3]
all rows visited

For the first row, the inner loop encounters 2 and breaks, skipping its inner else. For the second row, the inner loop exhausts its input and executes its inner else.

The outer loop itself has not been broken. After visiting both rows, it completes normally and executes its own else suite.

Loading diagram…

The scope of a break is crucial: it exits the innermost enclosing loop. It does not suppress the else clauses of all outer loops.

A helper function using return can exit an entire nested search if that is the intended behavior. Keep each level's completion policy explicit.

7. Return and exceptions are different from normal completion#

PYTHON
def probe(mode): for _ in range(1): if mode=='return': return 'returned' if mode=='error': raise ValueError('failed') else: return 'completed' print(probe('normal'),probe('return')) try: probe('error') except ValueError as exc: print(exc)

Output:

completed returned
failed

The normal invocation exhausts its one-item range and returns completed from the else suite. The return mode leaves the function directly from the loop body. The error mode raises an exception that leaves the loop and is caught by its caller.

Neither early-exit invocation reaches the else suite.

However, an exception handled inside a loop does not necessarily prevent normal completion:

PYTHON
for value in [0,2]: try: print(10//value) except ZeroDivisionError: print('invalid') else: print('traversal complete')

Output:

invalid
5
traversal complete

The first iteration catches its division error and continues normally. The second prints 5. The loop then exhausts its iterable, so else executes.

This distinction matters in batch-processing code. A loop else suite does not establish that every operation succeeded. If the program catches and handles failures inside the loop, the traversal can complete despite those failures. Track rejected items or success counts separately when required.

8. Interview example: testing whether an integer is prime#

A prime integer is at least two and has no positive divisors other than one and itself. To check for a nontrivial divisor, it is sufficient to test integers up to the square root of n: if n has a factor greater than its square root, its complementary factor is smaller.

PYTHON
from math import isqrt def is_prime(n): if n<2: return False for d in range(2,isqrt(n)+1): if n%d==0: break else: return True return False print([n for n in range(20) if is_prime(n)])

Output:

[2, 3, 5, 7, 11, 13, 17, 19]

The function accepts integers. Values below two return False before the loop. For n equal to two or three, the divisor range is empty, so the loop completes normally and returns True from else. For a composite integer, the first discovered divisor triggers break and the final return False.

The isqrt function returns the floor of the exact square root of a nonnegative integer. Using it avoids relying on a rounded floating-point square root when determining integer bounds.

The worst-case number of divisor tests is O(sqrt(n)) for positive n under a unit-cost arithmetic model. The cost of arbitrary-precision integer arithmetic depends on operand bit length, so this simple trial-division algorithm is not efficient for very large integers. It is a teaching example, not a cryptographic primality test.

The verification suite compared the function against an independent exhaustive-divisor predicate for all integers from -10 through 999, including values below two, primes and composites.

9. When an early return is clearer#

PYTHON
def first_negative(values): for value in values: if value<0: return value return None print(first_negative([2,-3,-4]),first_negative([]))

Output:

-3 None

Here the first matching value completes the whole function. An early return is simpler than using break, assigning a result and adding a loop else suite. The final return None represents ordinary exhaustion without a match.

Use loop else when there is a meaningful difference between a break and normal completion, particularly when the surrounding function needs to continue afterward. Use an early return when the search result completes the function. For pure existence or universal-condition checks, the built-ins any and all may express the task more directly. They also short-circuit their iteration; all over an empty iterable is True, while any over an empty iterable is False.

Avoid relying on these alternatives as mechanically interchangeable transformations. Consider side effects, evaluation order, error handling and whether subsequent code must run.

10. Loop else versus other else clauses#

ConstructWhen else executes
if-elseThe if condition is false
if-elif-elseAll preceding conditions in the chain are false
for-elseThe iterator is exhausted normally
while-elseThe loop condition becomes false
try-except-elseThe try suite completes without an exception or a return, break or continue that leaves it

The indentation and enclosing statement determine the meaning of else. A loop else suite is not a fallback for each false if condition inside the loop. It runs at most once for each execution of that loop statement.

The try statement's else clause also has a normal-completion flavor, but its rules are tied to the try suite rather than the iteration mechanism. Exception handling is a separate topic in the curriculum.

11. Common mistakes and best practices#

MistakeCorrect understanding
Else runs only when the loop has zero iterationsIt also runs after ordinary completion of a nonempty traversal
Else runs whenever there was no breakA return or escaping exception can bypass it too
Continue suppresses elseContinue can still lead to normal completion
Inner break suppresses outer elseEach loop has its own exit and completion rules
Else proves every item succeededHandled failures or skipped work may still lead to normal completion
Else belongs to the if inside the bodyAlign it with the intended loop header
Loop else is always necessaryAn early return, any, all or explicit state may be clearer

Test the empty case, match at the first and last position, no match, and the relevant exception paths. Where nested loops are involved, verify each level separately.

Use a descriptive function name and a clear break condition so that the reason for normal completion is easy to understand. Avoid complicated control flow inside finally suites that can override pending transfers.

Frequently asked questions#

Does for-else work with an empty list?#

Yes. The iterator is exhausted immediately, so the else suite executes even though the loop body never runs.

Does while-else execute when the condition is false initially?#

Yes. The false condition ends the loop normally.

Does break always skip else?#

A break that actually exits the relevant loop skips that loop's else suite. It does not automatically skip the else suite of an enclosing outer loop. Cleanup or another control transfer can also affect the final execution path.

Is else required after a loop?#

No. It is optional for both for and while.

Can loop else replace a found flag?#

Yes, for many search patterns. If a match triggers break, the else suite represents ordinary completion without that break. If other exit conditions exist, ensure that this interpretation still matches the actual business rule.

Interview-ready answer#

In Python, an optional else clause on a for or while loop executes when the loop completes normally: iterator exhaustion for for, or a false condition for while. A break exiting that loop skips its else suite; return and escaping exceptions can also bypass it. Continue does not prevent else after normal completion. Empty loops can execute else. The construct is useful for searches and validation where an early break indicates a special result, while normal completion requires a different action. In nested loops, each else belongs to its own loop.

Official references#

Verification note: All nine runnable Python groups matched their documented outputs on CPython 3.13.5 in independent namespaces. An additional 1,010 primality assertions passed. The three triple-backtick fenced Mermaid diagrams were manually reviewed; the local Mermaid CLI and package were unavailable, so parser validation and public-site rendering were not performed. Official links are supplied under the authorized offline research exception. Live documentation and the Supabase changelog were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design