Life-time of temporary variables in list comprehensions

Carsten Haese carsten at uniqsys.com
Tue Oct 23 13:20:30 EDT 2007


On Tue, 2007-10-23 at 17:02 +0000, beginner wrote:
> Hi All,
> 
> If I have a list comprehension:
> 
> ab=["A","B"]
> c = "ABC"
> [1.0 if c=='A' else c='B' for c in ab]

"c='B'" is invalid syntax. Maybe you mean "c=='B'". That doesn't make
much sense, but at least it's correct syntax.

> print c
> 
> >>"B"
> 
> 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.
> 
> My question is why is this and is there any way to make c local to
> list comp?

The only way to keep c from being overwritten currently is to avoid
using a list comprehension. Generator expressions don't "leak" their
iteration variable to the outside, so you can write this instead:

list(1.0 if c=='A' else c=='B' for c in ab)

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list