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
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)
Found 7 at index 3 6 is not in the list
How it works
- When the target is found,
breakends the loop and theelseblock does not run. - When the loop checks every item without finding it, there was no
break, so theelseblock runs. - Read the
elseas "no break". It belongs to thefor, not to theifinside it, so it is indented at the same level asfor.
The same search with a flag
Without for-else, you need an extra variable to remember whether the item was found:
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")
6 is not in the list
A prime number check
for-else also fits checks like "does any number divide this one?":
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")
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.