The for/else statement in Python

python for else statement


One of the first things you usually learn when starting a new language is the if-else construct of that language. Python, like some other languages, offers an extended variation of this called the “for/else” statement. Let’s check out a couple examples to see how it works!

The for/else statement

The main use case for the for/else statement is when you need to loop through a list with the potential to break out of the loop. If a break occurs in the loop, the code within the else clause will not be executed. However, if a break does not occur, then the code within the else clause will be executed.

For example, in the code below we initialize test = False. Then we loop through each element in the list, nums. If an element in nums equals 20, we break out of the loop. Since no element equals 20, we never break out of the loop, and therefore, the else clause is executed, which changes the value of test to equal True.



nums = [10, 4, 6, 8, 2]
test = False
for num in nums:
    if num == 20:
        break
else:
    test = True


python search list for else statement

In general, rather than just flagging a variable as True / False, you might want to perform some additional actions based off whether the break occurred.


nums = [10, 4, 6, 8, 2]
test = False
for num in nums:
    if num == 20:
        # do something here if 20 is found...
        break
else:
    test = True
    # do additional code here in case 20 is never found...

while/else statements

In addition to for/else statements, Python also supports while/else statements. We can modify our code above to use a while/else statement like this:


nums = [10, 4, 6, 8, 2]
test = False
i = 0
while i in range(len(nums)):
    if nums[i] == 20:
        break
    i += 1
else:
    test = True

Conclusion

That’s it for now! If you liked this post, please share with your friends, or subscribe to get notified about future posts!