[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Odd behaviour with list comprehension

Jerry Hill

3/1/2008 4:35:00 AM

On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu <kenpuca.dev@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:

>>> list(x for x in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
x
NameError: name 'x' is not defined
>>>

You have to pass it to the list constructor to get a list out of it,
though. For more on generator expressions see PEP 289:
http://www.python.org/dev/peps...

--
Jerry
1 Answer

Micah Cowan

3/1/2008 4:47:00 AM

0

"Jerry Hill" <malaclypse2@gmail.com> writes:

> On Fri, Feb 29, 2008 at 10:01 PM, Ken Pu <kenpuca.dev@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.

--
Micah J. Cowan
Programmer, musician, typesetting enthusiast, gamer...
http://micah.c...