Questions about list-creation

Mel mwilson at the-wire.com
Mon Nov 30 19:28:18 CET 2009


Manuel Graune wrote:

> 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

Long ago, lists were built using explicit code:

a = []
for i in xrange(10):
    a.append (i)

which of course left i bound to the last value that was appended.

People decided later that this was wordier than it had to be, and could bury 
the real point of a computation under a lot of boilerplate code that 
initialized lists, so we got list comprehensions, as you note, and they 
behave the same as the original code.

> using the similar code
> 
> b=list(j for j in xrange(10))
> 
> the local variable is destroyed after use:

The list constructor is a lot more recent.  It takes any iterable as an 
argument and makes (or tries to make) a list with the resulting values.  The 
example you give takes a sequence comprehension as its argument.  A sequence 
comprehension doesn't create data values -- it creates a block of code that 
can be executed later to create data values, and it can be executed later in 
any context.  So we could also code (untested):

def S():
    return (j for j in xrange (10))

def T(s):
    return list (s)

c = S()
b = T(c)

which still creates a list, but at an astonishing remove.  The sequence 
comprehension `c` can't count on finding a `j` in the namespace it finally 
gets executed in, so it has to have it's own private namespace to use then.

That's why you don't see `j` in your local namespace when `list` finallty 
runs the sequence comprehension.

	Mel.





More information about the Python-list mailing list