Else clause for Python's for loop

・1 min read

Photo by Kelly Sikkema on Unsplash

Not everyone knows, but there is an "else" clause for For loops.
I often see this:

did_something = False
for element in elements:
    if element.something:
        did_something = True

if not did_something:

But it should be like this:

for element in elements:
    if element.something:

Else clause executes only if the for loop exits naturally, without any break statements. That simple.


Kind of cool, but I think it would be more readable to separate the loop into its own function, returning true if element.something and returning false otherwise after looping thru. It would be much less confusing to look at, IMO.


It's no intuitive to me. I need to check documentation again every time encountered this to understand what it supposed to mean, which is a bad sign for language feature. Imagine having to check docs every time you encounter if ... else.

Jinja also has for ... else construct but the else will be executed if the loop not executed, like when the list is empty. This is intuitive to me, as it similar to how if ... else work. Either the primary block executed, or the else.


I use this feature all the time. My editor template for python's for block has an else clause that calls my log package. My coding style calls for loops to used if their coded

Classic DEV Post from Dec 27 '18

Even the Big Ones Mess Up

This morning, my feed blew up due to my friends and family complaining about so...

Maria Boldyreva
A coder.
Sign In

Follow the languages and libraries you care about.

Happy coding ❀️