goldb.org home

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.
Visit the new blog at: http://coreygoldberg.blogspot.com



 Wednesday, October 24, 2007

Python - List Comprehensions Leak Variables

One thing to remember when using List Comprehensions is that they "leak" their temporary iteration variable to the outside.

what does that mean?

In the following example, we still have access to 'x' after we run the list comprehension.

foo = ['a', 'b', 'c']
my_list = [x for x in foo]
print x

output:
>> c

This behaviour is different from how a Generator Expression works. We could have wrote the List Comprehension using a Generator Expression like this:

my_list = list(x for x in foo)

Now, the temporary variable we used is not accessible from outside the scope of the expression.

foo = ['a', 'b', 'c']
my_list = list(x for x in foo)
print x

output:
>> NameError: name 'x' is not defined

Note: This is fixed in Python 3000

#    Comments [5] |
Thursday, October 25, 2007 8:16:29 AM (Eastern Standard Time, UTC-05:00)
Spent some time tracking a problem caused by leaked values did we? (That's usually where I come up with posts like this) :)

-adan
Thursday, October 25, 2007 8:20:08 AM (Eastern Standard Time, UTC-05:00)
yup.. was having a prob and that was it :)
Thursday, October 25, 2007 12:34:11 PM (Eastern Standard Time, UTC-05:00)
interesting, just testet it and leaking actually means rebinding x, I guess that was the problem you ran into, or not?
Thursday, October 25, 2007 9:45:11 PM (Eastern Standard Time, UTC-05:00)
That's bitten me before, too. Any idea why on earth it works that way?
Monday, October 29, 2007 5:55:15 AM (Eastern Standard Time, UTC-05:00)
Hi Corey,

Interesting observation. This is quite a subtle problem arising from the way Python sees the scope of a variable in list comprehension.

Though I did not happen to come across this problem so far, but I guess, after reading your post, now I never will :-)!

Regards,
Rahul Verma.
Comments are closed.