else with for Loop in Python

In Python, a for loop can have an else block that executes only if the loop completes normally (i.e., it did not encounter a break).

If the loop is terminated by a break statement, the else block is skipped.

Syntax

for item in sequence:
    # loop body
    if condition_to_break:
        break
else:
    # executes if loop did NOT encounter break

Example:

Python

for i in range(5):
    print(i)
else:
    print("Loop finished")

Output 0
1
2
3
4
Loop finished

The else block runs because there was no break.

Example: Loop terminated with break.

Python

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        print("Breaking the loop")
        break
    print(num)
else:
    print("Loop completed without break")

Output 1
2
Breaking the loop

The else block does not run because the loop was terminated by break.

Example: Searching in a List.

Python

fruits = ["apple", "banana", "cherry"]
search = "mango"

for fruit in fruits:
    if fruit == search:
        print(f"{search} found!")
        break
else:
    print(f"{search} not found in the list")

Output mango not found in the list

The else is handy for search loops — it runs only if the item wasn’t found.