Python for loop else clause

Introduction

In this post, we are going to discuss a rarely used Python feature. We are familiar with the regular for and while loops but using an else clause after a loop is not common. We can live without this language feature however it can be used to write elegant code. Let us take an example…

As you can see, the code snippet above is straight forward. It linearly searches a list of numbers until it finds the number we are looking for (which is 7) otherwise the number is not in the list. Now, take a look at the following snippet:

For loop else break

The code snippet above performs the same thing as the previous one. The only difference is that the second one looks cleaner and shorter. Yes it is that simple. Some developers do not like this syntax because (to them) it does not make much sense. Anyway, it is a language feature, you can use it or ignore it, it is up to you.

How does it work?

An else clause after a for loop is only executed if the loop completes and finishes normally. In our case, there is a break statement that gets executed when number 7 is found. In that case, the else clause is not executed, however if 7 is not found then the break statement will not execute and the loop will finish normally. In this case, the else clause will execute. There is no reason for confusion. It is just a language feature to write better code. Do not use it if you do not want to. I hope this post was useful.

Thanks for visiting. For questions and feedback, please use the comments section below.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *