Odd behaviour with list comprehension

Jeffrey Froman jeffrey at fro.man
Sat Mar 1 05:58:07 CET 2008

Ken Pu wrote:

> So the list comprehension actually creates a variable x which is
> somewhat unexpected.
> Is there a way for me keep the iterating variable in list
> comprehension local to the list comprehension?

Not with a list comprehension, but generator expressions do not leak their
iterating variable:

>>> list(x for x in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined


More information about the Python-list mailing list