Odd behaviour with list comprehension

Steve Holden steve at holdenweb.com
Sun Mar 30 21:18:51 EDT 2008


Micah Cowan wrote:
> "Jerry Hill" <malaclypse2 at gmail.com> writes:
> 
>> On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu <kenpuca.dev at gmail.com> wrote:
>>>  Is there a way for me keep the iterating variable in list
>>>  comprehension local to the list comprehension?
>> Kind of.  You can use a generator expression instead of a list
>> comprehension, and those don't leak their internal variables into the
>> enclosing scope:
> 
> Whoa, that's cool. I didn't even think to try that, just assuming it
> would do the same.
> 
> Though now that I think about it, I don't see how it possibly could,
> since it just evaluates to an object that you could pass around, and
> return, using it the same way elsewhere.
> 
Well, the fact that the bound variable in the list comprehension does 
indeed remain outside the construct is simply the result of an 
over-zealous wish to emulate for loop semantics. The original reasoning, 
IIRC, as that since a for loop left its bound variable at the last used 
value, so should a list comprehension.

This was quickly recognized as a mistake, but unfortunately not quickly 
enough. As it was felt that some people might already have relied on 
that behavior, it was retained in the interests of preserving backwards 
compatibility.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list