for/else and while/else

An else attached to a loop, which runs only when the loop was never broken out of - and is misread by almost everyone the first time.

Overview

An else attached to a loop, which runs only when the loop was never broken out of - and is misread by almost everyone the first time.

In this guide
  1. The rule, exactly
  2. What it replaces
  3. Where it genuinely reads well
  4. while/else too
  5. Should you use it
  6. The name is the whole problem
  7. The shape it belongs to
  8. When not to use it
  9. Knowing it matters more than using it
  10. The same else, on try
  11. A worked example: searching nested data
  12. Where it sits among break and continue
  13. Reading it in real code
  14. Why it is still in the language
  15. Testing a loop that has one
  16. Questions people ask about for/else and while/else
  17. for/else and while/else: recap in one screen

loop_else.py

loop_else.py Python 3
Output

                    

loop_else_uses.py

loop_else_uses.py Python 3
Output

                    

Worth knowing

The else runs when the loop ended normally - no break.
It is not "else if the loop did not run". An empty loop still runs the else.
Think of it as nobreak. That is the name it should have had.
It replaces the found = False flag, which is the pattern it exists for.

for/else and while/else: A Practical Guide

A loop can have an else. It runs when the loop finished most times. That is, when no break happened. Almost everyone reads it as "else if the loop didn't run". That isn't what it means.

The rule, exactly

for item in items:
    if item == target:
        break
else:
    print("not found")

The else runs if the loop completed without hitting break. Iterate zero times? The else runs. Iterate a million times and finish normally? The else runs. Break out on the first pass? It does not run.

The keyword is badly chosen. If it had been called nobreak, no one would ever have been confused by it. Reading it that way in your head is the fastest way to make it click.

The pattern solves a specific problem. Without loop else, you need a flag variable to track whether the loop found what it was looking for. You set found = False before the loop, set it to True when you find the item, and check it after the loop. That is four extra lines and one more variable to track. The else clause does the same thing with zero extra variables.

The same syntax works with while loops. A while loop with an else runs the else block when the condition becomes false naturally. If the loop exits via break, the else is skipped. The logic is identical to for/else.

Most Python programmers rarely use this feature, and some style guides discourage it because the keyword else suggests "if the loop did not run" rather than "if the loop did not break." But in the specific case of searching for an item and needing a fallback when the search fails, it produces clean, readable code.

The most common use case is searching through a collection and raising an exception or printing a message when the item is missing. Another common use case is checking whether a number is prime: loop through potential divisors, break when you find one that divides evenly, and use the else clause to confirm the number is prime.

This page covers the exact rule, how it works with for and while, what it replaces, and why the naming trips up beginners.

What it replaces

This shape appears constantly:

found = False
for item in items:
    if match(item):
        found = True
        break
if not found:
    ...

The flag exists only to carry one bit of info past the end of the loop. for/else carries it for you. The else block is the "we never found it" branch. One fewer variable. One fewer chance to forget to set it.

Where it genuinely reads well

Searching, and primality testing, which is the same shape:

for i in range(2, int(n ** 0.5) + 1):
    if n % i == 0:
        return i
else:
    return None

"Tried each divisor, none worked" is just the else branch.

while/else too

The same rule applies to while: the else runs when the rule became false. Not when a break ended the loop. That maps onto retry loops neatly. The else is where "we exhausted each attempt" lives.

Should you use it

It's a genuine tool and it's also unseen to many readers. Inside a small function whose whole point is the search, it reads well and saves a flag. Buried in a long function among other loops, a comment or a flag may serve the next person better. Knowing it matters more than using it. You'll meet it in other people's code and it must not be a mystery.

The name is the whole problem

Nothing about the word "else" suggests "if the loop wasn't broken out of", and that mismatch is why the feature has a reputation for being confusing rather than for being handy. The action itself is simple and has no edge cases.

Guido van Rossum has said the keyword was a mistake and that a thing like nobreak would have been clearer. Reading it that way in your head is truly all it takes. The confusion disappears right away and doesn't come back.

The shape it belongs to

for/else fits one exact shape: a search that must report failure. Loop over picks, break when you find one. The else is the "we got to the end without finding any of it" branch.

That shape appears more often than it first seems - looking up a record, validating that no item breaks a rule, testing divisibility, scanning for a delimiter. In each case the option is a boolean flag that exists only to carry one bit of info past the end of the loop, and each flag is a chance to forget to set it or to check it in the wrong place.

When not to use it

If the loop has no break, the else always runs and is so pure decoration - it means just the same as putting the code after the loop, but makes a reader stop and work that out. Delete it.

If the function can simply return from inside the loop, that is often clearer than either version, because the "not found" case turns the last line of the function rather than an attached block:

def find(items, target):
    for item in items:
        if item == target:
            return item
    return None

Most searches inside a function are better written this way. This Is part of why for/else stays uncommon even among people who know it.

Knowing it matters more than using it

The reason to learn this feature is that you'll read it. It appears in the standard library and in other people's code, and an unseen make in someone else's loop is just the kind of thing that makes a reader guess. Guessing wrong here is easy, because the plain-English reading of "else" is the opposite of the truth in the case people often check first - the empty sequence, where the else still runs.

The same else, on try

else appears in a third place in Python, and seeing it there's what makes the loop version stop feeling any:

try:
    value = int(text)
except ValueError:
    print("not a number")
else:
    print("parsed", value)
finally:
    print("done")

The else on a try runs when no exception was raised. The else on a loop runs when no break happened. In both cases the block means *the thing we were guarding against didn't occur* — the exception didn't fire, the search didn't find an early exit.

Read that way, the loop version is steady with the rest of the language rather than an oddity bolted on. It's still a badly chosen keyword, because "else" in an if means "the rule was false" and in these two places it means "the interruption didn't happen". But there's one idea behind both, and knowing it's easier than storing two unrelated rules.

The try version has a second, hands-on reason to exist: it keeps the try block down to the line that can really raise. Code that should only run on success goes in the else. Here It isn't accidentally protected by the except, so an unrelated ValueError from the success path isn't silently caught by a handler meant for the parse.

A worked example: searching nested data

The shape for/else fits is a search that has to report failure, and nesting is where the flag-based option starts to hurt:

grid = [[1, 2], [3, 4], [5, 6]]

for row in grid:
    if 4 in row:
        print("found in", row)
        break
else:
    print("not found")
found in [3, 4]

Change the target to 9 and the else prints "not found". No flag, no variable that has to be was reset before the loop and checked after it, and the failure branch sits visually attached to the loop it belongs to.

The equal with a flag is four lines longer and has three places to make a mistake: losing to reset, losing to set it, and checking it with the wrong sense. None of those are hard mistakes to avoid, and all of them are mistakes that get made.

Where it sits among break and continue

The three of them show what happens to a loop. It helps to hold them together.

break leaves the loop right away, skipping the else. It's the only thing that skips the else, which is the entire rule.

continue skips the rest of the current iteration and goes on to the next one. It doesn't affect the else at all. A loop that continues each single time still finishes most times, and the else still runs.

return inside a loop leaves the function altogether. So The else never runs and neither does any of it after the loop. This is why a search written inside a function often doesn't need for/else: returning early makes the failure case the last line of the function. This Most readers find easier than an attached block.

The one that surprises people is the empty sequence. A loop over an empty list runs zero times, never breaks, and so *does* run its else. If you read else as "if the loop didn't run", this is just backwards, and it's the case worth testing yourself on.

Reading it in real code

The reason to learn a make you may choose not to write is that you'll meet it. for/else appears in the standard library and in long-lived codebases, often in just the search-and-report-failure shape given here, and at times in parsing code where a few loops each have their own failure branch.

When you meet one, the solid move is to find the break. If there's one, the else is the no-break branch and the loop is a search. If there's no break anywhere in the body, the else is decoration and means nothing at all — and that is worth noticing, because it's often a sign that somebody wrote it expecting a different action.

Why it is still in the language

Features this misunderstood often get removed, and this one hasn't been, which is worth a moment.

It can't be removed without breaking working code, and the amount of Python in existence that uses it's small but real. More to the point, the action is not wrong — it does a thing handy, has no edge cases, and the only complaint anyone makes is about the keyword. Changing the keyword would break just as much code as dropping the feature, and adding nobreak as a synonym would mean two ways to write one thing. This The language actively avoids.

So it stays, mildly awkward and at times handy, and the hands-on spot for anyone learning Python is the one this page has taken throughout: learn to read it fluently, and make your own choice about writing it. Neither choice is wrong. What is wrong is meeting one in unseen code and guessing.

Testing a loop that has one

If you do write for/else, it has two paths and both deserve a test, which is easy to forget because the failure path has no code of its own to point at.

The three cases that matter are: the item is found. So The break fires and the else is skipped. The item is absent from a non-empty sequence, so the loop finishes and the else runs. And the sequence is empty, which also runs the else. That third case is the one most likely to be missing from a test suite and most likely to be wrong in the code. It's the case where the plain-English reading of "else" and the actual action disagree.

If the empty case should behave differently from the not-found case — and at times it should, because "you gave me nothing to search" isn't the same answer as "I searched and it isn't there" — then for/else can't express that on its own, and an clear check before the loop is the honest way to say it.

Questions people ask about for/else and while/else

Does the else run if the loop body never executes? Yes. Zero iterations means no break, so the else runs. This is the case most people guess wrong.

Does continue skip the else? No. Only break does.

Does return inside the loop run the else? No — the function has already left.

Does an exception skip the else? Yes, unless it's caught inside the loop. The exception passes and nothing after the loop runs.

Can I use else on a comprehension? No. The else you can write inside a comprehension is part of a if-based formula, which is an unrelated feature.

Is there an else for while? Yes, with the same rule: it runs when the rule became false, and not when a break ended the loop.

Should I use it in code others will read? In a short function where the loop is a search, yes. Buried in a long function, a comment or an early return may serve the next reader better.

Do other languages have this? Very few. It comes from a long-standing idea in structured programming, and Python is the mainstream language most associated with it. This Is part of why it's unseen.

Does a linter complain about it? Some flag a loop else with no break in the body. This Is just the case where it means nothing. That is a handy warning to have switched on.

Can I use break inside a nested loop and reach the outer else? No. break leaves only the loop it's in, so it skips that loop's else and leaves the outer one to finish most times.

for/else and while/else: recap in one screen

  • The else on a loop runs when the loop finished without a break — read it as nobreak.
  • Zero iterations still counts as finishing. So The else runs for an empty sequence.
  • continue doesn't affect it. break and return are what skip it.
  • It replaces the found-flag pattern in searches, dropping a variable and two chances to be wrong.
  • The same else is on try, meaning the same thing: the interruption did not happen.

Check yourself

0 of 3

Answer without scrolling back up.

  1. When does a for/else's else block run?

  2. What does for/else replace in ordinary code?

  3. `for x in []: pass` followed by `else: print('hi')` prints what?

Cheat sheet

for/else and while/else

Attach an else clause to a for or while loop so a block of code runs only when the loop finishes without hitting break.

PYTHON · vizlearn.in/python/loop_else.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.