Python is one of the most popular programming languages. You see posts about it all the time.
If you use it, you may have been seeing many tips about it all over the place: from tweets to articles, or YouTube videos.
Despite all that, chances are that you may have missed the following “for-else” which I also got to see for the first time a couple of weeks ago.
As mentioned in the title, this is a “for-else” method of looping through a list, where despite having an iteration through a list, you also have an “else” condition, which is quite unusual.
This is not something that I have seen in other programming languages like in Java, Ruby, or JavaScript.
Let’s see an example of how it looks in practice.
Let’s say that we are trying to check whether there are no odd numbers in a list.
Let’s iterate through it:
In case we find an odd number, then that number will be printed since break will be executed and the else branch will be skipped.
Otherwise, if break is never executed, the execution flow will continue with the else branch.
If we have the following list, 1 will be printed:
I hope you find this useful.
Happy learning!