Life-time of temporary variables in list comprehensions

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Oct 23 13:25:00 EDT 2007


On Tue, 23 Oct 2007 17:02:48 +0000, beginner wrote:

> My test shows that if c is not defined before the list comprehension, it
> will be created in the list comprehension; if it is defined before the
> list comprehension, the value will be overwritten. In other words, temp
> variables are not local to list comprehensions.

That's right.

> My question is why is this and is there any way to make c local to list
> comp?

It was a design decision that is now regretted. There is no way for you 
to make it local to the list comp except to wait for a new version of 
Python that behaves in the way you want.

Or you can look at generator expressions, which are written just like 
list comprehensions except with round brackets (). They are not quite the 
same thing, but you can often use one in place of the other.


-- 
Steven.



More information about the Python-list mailing list