Questions about list-creation

Luis Zarrabeitia kyrie at uh.cu
Mon Nov 30 15:22:12 EST 2009


On Monday 30 November 2009 12:22:17 pm Manuel Graune wrote:
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
[...]
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:

Actually, [] and list() are not the same. For instance, list(1,2) rises an 
error, while [1,2] is the list with two elements.

The comprehension is just a syntactic contruct that allows you to simplify the 
creation of lists, while the list() "function" (it is a class, actually) 
receives an iterable object and returns a list.

What you seem to be confused about is the construct:

(j for j in xrange(10))

That is called a generator expression, and it is very similar to the list 
comprehension, except that it builds an iterator (instead of a list, i.e, the 
xrange(10) is not consumed until it is needed), and the loop variable 
doesn't "leak" outside.

When you do b=list(j for j in xrange(10)), you are actually doing

b=list((j for j in xrange(10)))

(note the extra set of parenthesis - python lets you ommit those), i.e, you 
are calling the list() "function" with a single argument, an iterable that 
contains all the elements of xrange(10). You could be calling

foobar(j for j in xrange(10))

instead.

And I think I lost my way... I'm sleepy. If I confused you, sorry... and if 
I'm helped you, thank you for letting me :D.

Cya.

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie



More information about the Python-list mailing list