For-Else: A Weird but Useful Feature in Python

Use it properly and skilfully

Yang Zhou
TechToFreedom
Published in
3 min readApr 18, 2021

--

No matter which programming language we use, we all write “if-else” statements, but how about “for-else” ?

For many languages, such as C, C++ and Java, it’s totally wrong if you use an “else” after a loop. However, Python, as an elegant language, has this weird but useful feature. If we use it properly, our code will become neater and cleaner.

This article will introduce the “for-else” feature in Python and explain how to use it properly by simple examples.

The Basics of the “For-Else” Feature

The “for-else” feature looks strange and hard to understand when a Python developer encounters it for the first time. But in fact, its usage is unexpectedly simple. One sentence is enough to explain it:

The “else” block only executes when there is no break in the loop.

Too simple to be true? Let’s check it out by an example:

As shown above, the list leaders doesn’t contain “Yang”, so there is no break in the for loop. Therefore, the “else” block executed and printed the information.

What will happen if the leaders list includes “Yang”?

As shown above, since “Yang” is in the leaders list, the for loop was broken and the “else” block didn’t execute.

In a nutshell, the for-else feature is not too hard to understand. But using it properly and skilfully is not easy. There are at least three scenarios suitable for the for-else feature.

3 Scenarios To Use the For-Else Feature

--

--