Mailing List Archive

Why variable used in list comprehension available outside?
Hi,

The following example demonstrates the variable 'v' used in the list
comprehension is accessible out site the list comprehension.

I think that 'v' should be strictly local. Does anybody know where
this behavior is documented and why it is designed this way?

~/linux/test/python/man/library/__buildin__/class/{/iteritems$ cat main1.py
#!/usr/bin/env python

d = {'one': 10, 'two': 20}

for k, v in d.iteritems():
print k, v
x=[2*v for v in [1, 2, 3]]
print x
print k, v
~/linux/test/python/man/library/__buildin__/class/{/iteritems$ ./main1.py
two 20
[2, 4, 6]
two 3
one 10
[2, 4, 6]
one 3


--
Regards,
Peng
--
http://mail.python.org/mailman/listinfo/python-list
Re: Why variable used in list comprehension available outside? [ In reply to ]
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@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@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



--
http://mail.python.org/mailman/listinfo/python-list