else Clause on for Loop

Python offers the else statement to complement control flow structures, such as the for loop. It is a unique capability that many programming languages do not have. This ’else’ clause executes when the for loop finishes its iteration without encountering a break statement.

Basic Syntax

Here’s the basic syntax for the else clause with a for loop:

1for variable in iterable:
2    // for loop code here
3else:
4    // else clause code here

The for loop goes through each element of the iterable one by one. If the loop finishes naturally, without facing a break statement, it will then execute the code within the else clause.

Full Use Case Example

Let’s consider a real-life application. We may use a for loop to search an element in a list:

1my_list = [1, 2, 4, 3, 5]
2search_item = 7
3
4for item in my_list:
5    if item == search_item:
6        print("Item found in list!")
7        break
8else:
9    print("Item not found in list.")

In this block of code, the for loop goes through my_list, and the if statement checks if the current item is equal to search_item. If it finds a match, it will print “Item found in list!” and break the loop. If the for loop finishes iterating over my_list without finding search_item (hence no break statement encountered), the code within the else block will run, printing “Item not found in list.”

Note

The else clause on a for loop will NOT execute if the loop gets terminated by a break statement.

Conclusion

The else clause on a for loop is a useful tool for enhancing control of your code. It gives you a way to specify some code that should only run if the for loop completed naturally, without break. Understanding this can help you make your Python programs more efficient and clear.