Python list comprehensions nasty behavior

Sat 19 April 2008 | tags: python

Python’s list comprehension syntax is amazingly concise and easy to use and understand. It make Python even more beautiful than it already is.

However, i came upon some weird behavior today that caused a strange bug in my application.

The common way to use a list comprehension is with a variable named x eg:

my_new_list = [ for x in people ]

The behavior most of us would expect (or assume to be reasonable) is for the scope of variable x to be limited within the execution of the list comprehension.

This is not the case however. If you already have defined an x variable and expect it to be the same after the list comprehension you will be disappointed (not to mention bewildered at your new,  seemingly unexplained, bug ).

I am not sure why this feature it was designed that way. I think this is a source of confusion and, as such, un-pythonic, if i may use the term :-)

Be careful when using list comprehensions to use a completely new variable.

Comments !