0

Possible Duplicate:
Python list comprehension overriding value

I did some googling around, but no solutions to this issue. It seems like list comprehensions mess with the current namespace, which seems really odd to me.

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

The first is an error, the second prints range(10) as expected, and the last line prints 9, the 'last value of i' for the list comprehension. This is completely unexpected to me. What's more, if i was previously defined, it's now been overwritten.

I'm running on Apple's build of Python 2.7 (OS X Lion), if that means anything.

Community
  • 1
  • 1
Kurt Spindler
  • 1,310
  • 1
  • 14
  • 22
  • In Python 2.x, list comprehensions leak the loop variable. This behavior was changed in 3.x – JBernardo Oct 12 '11 at 04:46
  • 1
    It's for this reason that some developers advocate using very short (1–2 letter) variable names for loop variables within list comprehensions, and using longer, more descriptive names elsewhere (e.g. `cs` as loop variable, `changeset` elsewhere). This convention helps to avoid accidentally clobbering variables. – davidchambers Oct 12 '11 at 04:53

0 Answers0