Questions about list-creation

Lie Ryan lie.1296 at gmail.com
Mon Nov 30 13:13:48 EST 2009


On 12/1/2009 4:22 AM, Manuel Graune wrote:
>
> Hello,
>
> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing. For example "help([])" and "help(list())" point
> to the same documentation. Since there are at least
> two cases where this similarity is not the case, (see below)
> can someone explain the reasoning behind this and point to
> further / relevant documentation?
> (To clarify: I am not complaining about this, just asking.)
>
>
> 1.)
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
>
> print "a",a
> print "i",i
>
> using the similar code
>
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:
>
> print "b",b
> print "j",j


It's not so much about list() vs. [] but generator comprehension vs. 
list comprehension. list() takes a generator comprehension, while 
[listcomp] is its own syntax. List comprehension leaked its "loop 
counter" to the surrounding namespace, while generator comprehension got 
its own tiny namespace.

This "bug" (or feature, depending on your political alignment) is fixed 
in Python 3.x:

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> a = [i for i in range(10)]
 >>> i
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
 >>> a = list(i for i in range(10))
 >>> i
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
 >>> ^Z




More information about the Python-list mailing list