[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.python

Odd behaviour with list comprehension

Ken Pu

3/1/2008 3:02:00 AM

Hi all,

I observed an interesting yet unpleasant variable scope behaviour with
list comprehension in the following code:

print [x for x in range(10)]
print x

It outputs:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9

So the list comprehension actually creates a variable x which is
somewhat unexpected.
Is there a way for me keep the iterating variable in list
comprehension local to the list comprehension?

Any comments on the current behaviour of Python is greatly appreciated.
Ken
2 Answers

Micah Cowan

3/1/2008 4:20:00 AM

0

"Ken Pu" <kenpuca.dev@gmail.com> writes:

> Hi all,
>
> I observed an interesting yet unpleasant variable scope behaviour with
> list comprehension in the following code:
>
> print [x for x in range(10)]
> print x
>
> It outputs:
>
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> 9
>
> So the list comprehension actually creates a variable x which is
> somewhat unexpected.

Yeah, it's not really desired, either. The Python Reference Manual,
in the "List Displays" section, has this footnote:

In Python 2.3, a list comprehension "leaks" the control variables of
each "for" it contains into the containing scope. However, this
behavior is deprecated, and relying on it will not work once this
bug is fixed in a future release.

In the meantime, of course, we can't depend on it _not_ leaking,
either.

> Is there a way for me keep the iterating variable in list
> comprehension local to the list comprehension?

Not really, AFAIK. Other than to do it within a separate block, of
course, but that's rather cumbersome (writing a new function would do
it, but that's more trouble than it's worth).

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

Jeffrey Froman

3/1/2008 4:58:00 AM

0

Ken Pu wrote:

> So the list comprehension actually creates a variable x which is
> somewhat unexpected.
> Is there a way for me keep the iterating variable in list
> comprehension local to the list comprehension?

Not with a list comprehension, but generator expressions do not leak their
iterating variable:

>>> list(x for x in range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined



Jeffrey