I wanted to have a list of lambdas that act as sort of a cache to some heavy computation and noticed this:
>>> [j() for j in [lambda:i for i in rang
I'm not sure if it's a bug or a feature, but what's happening is that lambda:i doesn't evaluate i before forming the lambda function. So, it's literally just a function which evaluates whatever the current value of i is. Here's another example of how this happens.
>>> i=5
>>> x=lambda:i
>>> x()
5
>>> i=6
>>> x()
6
So, obviously, what's happening is the same thing except that i is going to 9 in your examples as it's being assigned through the range 0 through 9 in that order.
I don't think that there's really any good way to avoid it. Lambda functions in Python are pretty limited. It's not really a functional language at heart.