• From: Luis Zarrabeitia <kyrie@xxxxx>
• Date: Mon, 30 Nov 2009 15:22:12 -0500

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))

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
.

## Relevant Pages

• Clashing of local variable names and symbolic inputs to procedures
... convert simple series into continued fraction expansions: ... (I tried it with several lists of rationals, ... changed the names of the argument, and some of the local variables, and then ... possible clash with something symbolic in the input list. ...
(sci.math.symbolic)