Odd behaviour with list comprehension

Micah Cowan micah at cowan.name
Sat Mar 1 05:20:17 CET 2008


"Ken Pu" <kenpuca.dev at 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.cowan.name/



More information about the Python-list mailing list