loop scope

Terry Reedy tjreedy at udel.edu
Fri Mar 12 15:52:11 CET 2004

<user at domain.invalid> wrote in message
news:405148CB.1030103 at domain.invalid...
> Terry Reedy wrote:
>> For list comps which cannot have break,
>> it is an artifact which may disappear in 2.4.
> If I understand you,

I don't think you did.  The 'may' only applies to list comprehensions.  The
discussion last fall was whether the index names(s) within a list
comprehension should be bound outside (after) the list comp.  It is
something of an accident of the current implementation that they are.  The
issue arose in the development of generator comprehensions, in which it was
clear that the within-generator variables would *not* be bound outside of
the produced generator.  Bret Cannon's summary
is this:

A quick example is:

(x for x in range(10) if x%2)

returns an iterator that returns the odd numbers from 0 to 10. This make
list comprehensions just syntactic sugar for passing a generator expression
to list() (note how extra parentheses are not needed):

list(x for x in range(10) is x%2)

Having list comprehensions defined this way also takes away the dangling
item variable for the 'for' loop. Using that dangling variable is now
discouraged and will be made illegal at some point.

Terry J. Reedy

More information about the Python-list mailing list