Odd behaviour with list comprehension

Jerry Hill malaclypse2 at gmail.com
Fri Feb 29 23:34:39 EST 2008


On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu <kenpuca.dev at gmail.com> wrote:
>  Is there a way for me keep the iterating variable in list
>  comprehension local to the list comprehension?

Kind of.  You can use a generator expression instead of a list
comprehension, and those don't leak their internal variables into the
enclosing scope:

>>> list(x for x in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    x
NameError: name 'x' is not defined
>>>

You have to pass it to the list constructor to get a list out of it,
though.  For more on generator expressions see PEP 289:
http://www.python.org/dev/peps/pep-0289/

-- 
Jerry



More information about the Python-list mailing list