Odd behaviour with list comprehension

K

Ken Pu

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
 
M

Micah Cowan

Ken Pu said:
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).
 
J

Jeffrey Froman

Ken said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top