Methods that use else statements in Python's loop body

  • 2020-04-02 14:48:07
  • OfStack

This article discusses Python's for... The else and while... Else syntax, one of the least used and most misunderstood syntax features in Python.

Both the for and while loops in Python have an optional else branch (similar to the if and try statements) that is executed after the loop iteration completes normally. In other words, if we do not exit the loop in any other way than the normal way, the else branch will be executed. That is, there are no break statements, no return statements, or no exceptions in the loop. Consider a simple (useless) example:
 


>>> for i in range(5):
...   print(i)
... else:
...   print('Iterated over everything <img src="http://python.jobbole.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley"> ')
...
0
1
2
3
4
Iterated over everything <img src="http://python.jobbole.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley">

In the code above, we iterate over range(5) and print each number. Because we let the loop complete normally, the else branch is also executed and printed Iterated over everything :). In contrast, if we terminate the loop with a break statement, the else branch will not execute:
 


>>> for i in range(5):
...   if i == 2:
...     break
...   print(i)
... else:
...   print('Iterated over everything <img src="http://python.jobbole.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley"> ')
...
0
1

Note that even though the sequence the loop iterates over is empty, the else branch will still be executed, and the loop will still complete normally.
 


>>> for i in []:
...   print(i)
... else:
...   print('Still iterated over everything (i.e. nothing)')
...
Still iterated over everything (i.e. nothing)

Don't forget, too, that all of the above applies to while... The else:
 


>>> i = 0
>>> while i <= 5:
...   i += 1
...   print i
... else:
...   print 'Yep'
...
1
2
3
4
5
Yep

But why! ?

A common use case for else statements in loops is to implement loop lookups. Suppose you are looking for an item that satisfies a particular condition and need to do additional processing, or generate an error when no acceptable value is found:
 


for x in data:
  if meets_condition(x):
    break
else:
  # raise error or do additional processing

In the absence of an else statement, you need to set a flag and then check it later to see if there is a value that satisfies the condition.
 


condition_is_met = False
for x in data:
  if meets_condition(x):
    condition_is_met = True
 
if not condition_is_met:
  # raise error or do additional processing

This is not something that really matters, and in many other languages you have to do it. But like many other features of Python, else statements can generate more elegant Pythonic code. No doubt in The above example, using The else statement makes The code more The Zen of Python friendly:

This doesn't mean you have to use else statements in loops, you can always use flags and so on. But else statements often make the code more elegant and readable. You might think this is Pythonic and makes the intent clearer (hey!). However, others may think this is confusing and redundant! Personally, I insist on using the else statement in the loop unless there is another, more readable method (I think the readability of the code is most important to me).


Related articles: