Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

Why variable used in list comprehension available outside?

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


pengyu.ut at gmail

May 2, 2012, 5:52 PM

Post #1 of 2 (324 views)
Permalink
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


python.list at tim

May 2, 2012, 6:23 PM

Post #2 of 2 (302 views)
Permalink
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 [at] bigbo:~$ 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] bigbo:~$ 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

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.