[Python-ideas] for/else syntax

Nick Coghlan ncoghlan at gmail.com
Sat Oct 3 17:22:25 CEST 2009


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:
> 
> http://docs.python.org/reference/compound_stmts.html#the-for-statement
> 
> Where it says (just as I did, but in other words):
> 
> "When the items are exhausted (which is immediately when the sequence
> is empty), the suite in the else clause, if present, is executed, and
> the loop terminates."

The code in your example is semantically identical to the following:

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

  if i > 0:
    # This block is unreachable...

Without a break statement in the body of the loop the else will by
executed unconditionally, hence it is exactly the same as if the code it
contains was just inline after the loop body.

The semantics you describe can be obtained only by initialising i before
the loop:

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

  if i >= 0:
    # We did something

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list