← Python lessons

Python for else: Run Code When a Loop Finds Nothing

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

A for ... else loop runs its else block only when the loop finished without hitting break. It is the clean way to say "searched everything, found nothing".

Read For loops and break and continue first.

Run code when no break happened

The else lines up with for, not with an if.

rolls = [3, 5, 2]
for roll in rolls:
    if roll == 6:
        print("Found a six")
        break
else:
    print("No six rolled")

No roll is 6, so the loop never breaks and the else block prints No six rolled.

Skip the else when break runs

rolls = [3, 6, 2]
for roll in rolls:
    if roll == 6:
        print("Found a six")
        break
else:
    print("No six rolled")

This time break runs, so only Found a six prints. The else block is skipped.

Choosing for else over a flag

Without else, you need a flag variable to remember whether the loop found something.

rolls = [3, 5, 2]
found = False
for roll in rolls:
    if roll == 6:
        found = True
        break
if not found:
    print("No six rolled")

Both versions print the same thing. for ... else saves the extra variable. A flag is clearer when you need the result later, or when readers on your team don't know for ... else.

Watch out: an empty loop runs else

The else block also runs when the loop has nothing to loop over, because no break happened.

rolls = []
for roll in rolls:
    if roll == 6:
        print("Found a six")
        break
else:
    print("No six rolled")

An empty list prints No six rolled. That is usually what you want for a search, but check it is right for your program.

Note: else is not "run if the loop body never ran" and not "run on every non-break pass". It runs once, after the loop, only if there was no break. while loops support else the same way. These examples use fixed lists; real searches often loop over input or file lines instead.

See also: While loops.

Your turn

Finish find_first() so it prints Found <word> for the first word that starts with letter, or No word starts with <letter> when none does. Use for ... else with a break.

def find_first(words, letter):
    for word in words:
        # add an if that prints "Found", word and breaks,
        # then an else on the for loop that prints "No word starts with", letter
        pass

find_first(["kiwi", "plum", "pear"], "p")
find_first(["kiwi", "plum", "pear"], "a")

Expected output

Found plum
No word starts with a