Python else on Loops
1Python Loop else: overview
The else block of a for or while loop runs once when the loop finishes normally, and is skipped when a break ends the loop.
Before this lesson: Python for Loops, Python break and continue
2Python Loop else: diagram
3Python Loop else: explained step by step
Loops can have an else block, and it does not behave like the else you know from if. It surprises almost everyone the first time, which is exactly why it deserves its own lesson. The short version: the else block runs when the loop finished on its own, and it is skipped when break ended the loop.
The rule in action
Here are two searches of the same guest list. The first one finds its guest and breaks, so the else is skipped. The second never finds its guest, runs out of items, and the else runs.
guests = ["Ana", "Raj", "Lee"]
for guest in guests:
if guest == "Raj":
print("Found Raj")
break
else:
print("Raj is not on the list")
for guest in guests:
if guest == "Max":
print("Found Max")
break
else:
print("Max is not on the list")Read it as "no break"
The word else is a poor name here, so give it a better one in your head: no break. Read the block as "if the loop ended with no break, do this". For a search, that means "I looked at every item and never found a match", which is exactly the moment you want to report "not found".
Only break skips the else. A continue does not, and neither does the loop simply running out of items. (A return or an error leaves even more than the loop, so the else does not run then either.)
An empty sequence still "finished"
A loop over nothing runs zero rounds, but it did finish normally, and no break happened. So the else block runs:
orders = []
for order in orders:
print("Packing", order)
else:
print("Loop finished, even with no orders")Keep this in mind when an empty list should be treated differently from "searched and found nothing". In that case check if not orders: first.
Classic use: is this number prime?
A prime number has no divisor between 2 and itself. The loop tries each possible divisor. If one fits, the number is not prime and there is no point trying the rest, so break. If none fit, the loop runs out and the else says the number is prime.
number = 29
for divisor in range(2, number):
if number % divisor == 0:
print(number, "is divisible by", divisor)
break
else:
print(number, "is prime")This simple version has a hole: for 0 and 1, range(2, number) is empty, the loop "finishes", and the else would claim they are prime. Handle numbers below 2 before the loop.
else works on while loops too
For a while loop, the else block runs when the condition becomes False, and is skipped when a break ends the loop earlier.
queue = ["Ana", "Raj", "Lee"]
vip = "Lee"
position = 0
while position < len(queue):
if queue[position] == vip:
print(vip, "is at position", position)
break
position += 1
else:
print(vip, "is not in the queue")The most common confusion: whose else is it?
The indentation decides who owns an else. An else lined up with the if belongs to that if, and it runs on every round where the condition was False. An else lined up with for or while belongs to the loop.
guests = ["Ana", "Raj"]
for guest in guests:
if guest == "Max":
print("Found Max")
else:
print(guest, "is not Max")This prints one line per guest, because the else belongs to the if. For the "not on the list" message, you want it to move left so it lines up with for.
When something else is clearer
for ... else is compact, but many programmers rarely use it, so readers may need a moment to decode it. A short comment such as # no break helps. Two alternatives are worth knowing:
- A flag variable is clearer when you need to know the result later, or when several things happen if nothing is found.
- A function with
return(you will meet functions soon) lets you return as soon as you find a match, with the "not found" case after the loop and noelseat all.
found = False
for guest in guests:
if guest == "Max":
found = True
break
if not found:
print("Max is not on the list")
Quick reference: Python Loop else
- Python Program to Check Prime Number — A prime number is a whole number greater than 1 that has no divisors other than 1 and itself; in Python you t…
4Python Loop else: syntax
for item in items:
if matches(item):
...
break
else:
# runs only if the loop was NOT ended by break
while condition:
...
if found:
break
else:
# runs when the condition became False (no break)
5Python Loop else: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
candidates = [9, 13, 15, 17]
for number in candidates:
for divisor in range(2, number):
if number % divisor == 0:
print(number, "is divisible by", divisor)
break
else:
print(number, "is prime")Expected output9 is divisible by 3
13 is prime
15 is divisible by 3
17 is prime
7Python Loop else: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1Four numbers to test, stored in
candidates. - Line 3The outer loop takes one number at a time.
- Line 4The inner loop tries every divisor from 2 up to
number - 1. - Line 5-7If a divisor fits exactly, the number is not prime. The message is printed and
breakends the inner loop, which also skips itselse. For 9 this happens at divisor 3; for 15 also at 3. - Line 8-9This
elselines up with the innerfor(line 4), so it belongs to that loop. For 13 and 17 no divisor ever matched,breaknever ran, and the inner loop ran out of divisors, so theelseprints that the number is prime. - Line 3-9Each number gets a fresh inner loop. 9 and 15 take the
breakpath, while 13 and 17 take theelsepath.
8Python Loop else: common mistakes
Lining the else up with the if
✗ Wrong
guests = ["Ana", "Raj", "Lee"]
for guest in guests:
if guest == "Max":
print("Found Max")
break
else:
print("Max is not here")✓ Right
guests = ["Ana", "Raj", "Lee"]
for guest in guests:
if guest == "Max":
print("Found Max")
break
else:
print("Max is not here")This else is indented under the if, so it belongs to the if and runs for every guest who is not Max. Move it left so it lines up with for.
Expecting else to run after a break
✗ Wrong
tasks = ["email", "STOP", "backup"]
for task in tasks:
if task == "STOP":
break
print("Doing", task)
else:
print("Finished")✓ Right
tasks = ["email", "STOP", "backup"]
for task in tasks:
if task == "STOP":
break
print("Doing", task)
print("Finished")The else block is for the no-break case only. If a line should run whether or not the loop was stopped, put it after the loop without any else.
Calling 1 a prime number
✗ Wrong
number = 1
for divisor in range(2, number):
if number % divisor == 0:
print(number, "is not prime")
break
else:
print(number, "is prime")✓ Right
number = 1
if number < 2:
print(number, "is not prime")
else:
for divisor in range(2, number):
if number % divisor == 0:
print(number, "is not prime")
break
else:
print(number, "is prime")A loop over nothing still finishes normally. Numbers below 2 need their own check before the loop starts.
Adding an else to a loop that has no break
✗ Wrong
for guest in ["Ana", "Raj"]:
print("Welcome", guest)
else:
print("Everyone welcomed")✓ Right
for guest in ["Ana", "Raj"]:
print("Welcome", guest)
print("Everyone welcomed")else only means something when the loop can be ended by break. Without a break, write the line after the loop with no else, so readers are not left hunting for the break.
9Python Loop else: exercises
Write your answer, then press Check. The checks run in your browser.
1. Is the username free?
Write code Easy ✓ CompletedLoop over taken. If a name equals wanted, print <name> is taken and break. If the loop finishes without a break, print <name> is available using an else block on the loop. With the starting data the output is a single line: dina is available.
taken = ["asha", "ben", "chen"]
wanted = "dina"
# for ... else here
taken = ["asha", "ben", "chen"]
wanted = "dina"
for name in taken:
if name == wanted:
print(wanted, "is taken")
break
else:
print(wanted, "is available")
2. Predict the else
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
count = 0
while count < 5:
count += 1
if count == 2:
continue
if count == 7:
break
print("count", count)
else:
print("else ran")
print("end", count)count 1
count 3
count 4
count 5
else ran
end 5
2 more exercises → 5 more examples
Questions learners ask
Why does a for loop have an else block in Python?
It lets you write "search, and if the search never succeeded, do this" without a flag variable. The else block runs when the loop finished without a break, so it is the natural place for the "not found" case. Read it as "no break".
Does the else of a loop run when the loop has no items?
Yes. An empty sequence means the loop finished without ever hitting break, so the else block runs. If an empty collection needs different handling from "searched and found nothing", test it with if not items: before the loop.
Should I use for-else or a flag variable?
Either works. for-else is shorter for a plain "not found" message. A flag, or storing the result in a variable that starts as None, is clearer when you need the result after the loop or when several things depend on it. Pick the version your readers will understand fastest.
Further reading
10Next lesson
Up nextPython Nested LoopsA nested loop is a loop written inside the body of another loop, so the inner loop starts over and runs completely for …Related:
Python for LoopsPython while LoopsPython break and continue
← Python break and continue · All Control Flow lessons · Practise in the IDE