[Python-ideas] for/else syntax

Masklinn masklinn at masklinn.net
Sat Oct 3 17:31:25 CEST 2009

On 3 Oct 2009, at 13:49 , Gerald Britton wrote:
> Sory Carl, I did NOT get it dead wrong.  The else is executed if the
> for loop falls through.  That's the whole idea.  Probably I should
> have set i to -1 in the else clause of the toy example though:
> for i, j in enumerate(something):
>  # do something
>  i += 1
> else:
> i = -1
> if i > 0:
>  # we did something
> If you don't think the else is executed when the for-loop falls
> through, then you should re-read the documentation, here:
Carl didn't dispute that point. In fact that's exactly the issue with  
your code: since you don't have any `break` statement in your `for:`  
loop, the `else:` clause will *always* be executed, whether  
`something` is an empty collection or not.

Thus, the following `if i > 0:` clause cannot under any circumstance  
be executed.

Your code (unless there is a break in the 'do something' part) is  
equivalent to:

     for i, j in enumerate(something):
         # do something
         i += 1
     i = -1

     if i > 0:
         # can never happen

More information about the Python-ideas mailing list