Flavors of `else` in Python

Python’s loop statements have a feature which most of us are unfamiliar with, an else clause. For loops also have an else clause The else clause executes when the loop completes normally(without encountering any break statements). The basic structure of a for/else loop:

Possible use cases:

  • Searching an item in a list/iterable: This can be achieved by running a loop and comparing each item. There are two scenarios in which the loop may end. The first one is when the item is found and we break the loop using the break statement. The second scenario is that the loop ends. Now we may want to know which one of these is the reason for a loops completion. One method is to set a flag and then check it once the loop ends. Another is to use the else clause.
  • Try/Else completion clause: Else clause can be used with try block. Else clause in a try statement means that the try block completed successfully i.e didn’t throw any exception.
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.