Odd behaviour with list comprehension

Terry Reedy tjreedy at udel.edu
Sun Mar 30 22:43:58 EDT 2008


"Steve Holden" <steve at holdenweb.com> wrote in message 
news:fspe8a$ptq$1 at ger.gmane.org...
| 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.

But it will not be retained in 3.0, as I understand it.
So best to not exploit the deprecated behavior.

tjr






More information about the Python-list mailing list