[Python-ideas] for/else syntax

Steven D'Aprano steve at pearwood.info
Fri Oct 2 05:07:25 CEST 2009

On Thu, 1 Oct 2009 09:00:21 pm Antti Rasinen wrote:

> To add further insult to the naming injury, the else branch suffers
> from the fact that 99.9% of the time, the for-loop contains an if:

Really? You've done a statistically significant survey of code in the 
wild and come to a figure accurate to one part in a thousand? Not just 
plucked a number straight out of thin air?

In my code, the figure is more like 20-40%. Choosing one representative 
module at random, only one in three for-loops include an if inside the 
loop. And when I use for...else, it's closer to 10%.

> for x in xs:
>     if cond(x):
>         break
>     # stuff
> else:
>     # more stuff
> My code pattern matching algorithm reads that as an indentation
> error. An else matches if so many times more often that decoding
> for..else requires unnecessary effort.

But then there are these:

for x in xs:
    if cond(x):

for x in xs:

They don't look anything like an indentation error to me.

Steven D'Aprano

More information about the Python-ideas mailing list