else Clause on for Loop
On this page
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:
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:
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.