Why variable used in list comprehension available outside?

Tim Chase python.list at tim.thechases.com
Wed May 2 21:23:30 EDT 2012


On 05/02/12 19:52, Peng Yu wrote:
> The following example demonstrates the variable 'v' used in the
> list comprehension is accessible out site the list
> comprehension.

It did in Python 2.x but has been fixed in 3.x:

tim at bigbox:~$ python3
Python 3.1.3 (r313:86834, Nov 28 2010, 10:01:07)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 42
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
42
>>>

tim at bigbox:~$ python2.6
Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 42
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
9
>>>


-tkc






More information about the Python-list mailing list