Odd behaviour with list comprehension

Ken Pu kenpuca.dev at gmail.com
Sat Mar 1 04:01:51 CET 2008


Hi all,

I observed an interesting yet unpleasant variable scope behaviour with
list comprehension in the following code:

print [x for x in range(10)]
print x

It outputs:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9

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?

Any comments on the current behaviour of Python is greatly appreciated.
Ken



More information about the Python-list mailing list