PythonMastery

for else in Python

A for loop can have an else block that runs only when the loop was not stopped by break. Use it to report 'not found' without a flag variable.

A for loop can have an else block. The else runs when the loop has gone through every item. If the loop ends with break, the else is skipped. This makes it a good fit for searching: break when you find the item, and use else for "not found".

The program

python
def search(nums, target):
    for i, n in enumerate(nums):
        if n == target:
            print(f"Found {target} at index {i}")
            break
    else:
        print(f"{target} is not in the list")

nums = [1, 3, 5, 7, 9]
search(nums, 7)
search(nums, 6)
output
Found 7 at index 3
6 is not in the list

How it works

The same search with a flag

Without for-else, you need an extra variable to remember whether the item was found:

python
nums = [1, 3, 5, 7, 9]
target = 6

found = False
for n in nums:
    if n == target:
        found = True
        break

if not found:
    print(f"{target} is not in the list")
output
6 is not in the list

A prime number check

for-else also fits checks like "does any number divide this one?":

python
for n in [7, 9, 13]:
    for d in range(2, n):
        if n % d == 0:
            print(f"{n} is not prime ({d} x {n // d})")
            break
    else:
        print(f"{n} is prime")
output
7 is prime
9 is not prime (3 x 3)
13 is prime

To only check whether a value is in a list, if target in nums: is shorter. for-else is for when the loop does other work too, such as finding the index or the divisor.

Related programs: while loop with else.

Learn the idea: Loops: for, while, and the Pythonic Patterns