DEV Community

Cover image for Else clause for Python's for loop
Maria Boldyreva
Maria Boldyreva

Posted on

14 5

Else clause for Python's for loop

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:
        do_something()
        did_something = True
        break

if not did_something:
    do_something_else()
Enter fullscreen mode Exit fullscreen mode

But it should be like this:

for element in elements:
    if element.something:
        do_something()
        break
else:
    do_something_else()
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
bl41r profile image
David Smith • Edited

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.

Collapse
 
k4ml profile image
Kamal Mustafa

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.

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay