Generator Comprehensions

Skip Montanaro skip at
Tue Jan 29 10:33:07 EST 2002

    >> I don't see any spurious locals:
    >> >>> def f(n):
    >> ...   l = [i for i in range(n)]
    >> ...   print locals()
    >> ...   return l
    >> ... 
    >> >>> f(5)
    >> {'i': 4, 'l': [0, 1, 2, 3, 4], 'n': 5}
    >> [0, 1, 2, 3, 4]

    hamish> I think the original author was referring to the very fact that
    hamish> 'i' is among the locals that you printed out.

Ah, well in that case, I can fall back on the excuse that "list
comprehensions are essentially syntactic sugar sprinkled on for loops".  ;-)

If you convert a list comprehension to its equivalent series of for loops,
if statements, and list appends, you wind up at the end with a loop index
variable that is not destroyed.  For example, the above is equivalent to

    l = []
    for i in range(n):

"i" doesn't go away after the for loop.  Nor does it after the list

Skip Montanaro (skip at -

More information about the Python-list mailing list