In python 2.6:
[x() for x in [lambda: m for m in [1,2,3]]]
results in:
[3, 3, 3]
I would expect the output to be [1, 2, 3]. I get the exact same problem even with a non list comprehension approach. And even after I copy m into a different variable.
What am I missing?
I noticed that too. I concluded that lambda are created only once. So in fact your inner list comprehension will give 3 indentical functions all related to the last value of m.
Try it and check the id() of the elements.
[Note: this answer is not correct; see the comments]
Long story short, you don't want to do this. More specifically, what you're encountering is an order of operations problem. You're creating three separate
lambda
's that all returnm
, but none of them are called immediately. Then, when you get to the outer list comprehension and they're all called the residual value ofm
is 3, the last value of the inner list comprehension.-- For comments --
Those are three separate lambdas.
And, as further evidence:
Again, three separate IDs.
Look at the
__closure__
of the functions. All 3 point to the same cell object, which keeps a reference to m from the outer scope:If you don't want your functions to take m as a keyword argument, as per unubtu's answer, you could instead use an additional lambda to evaluate m at each iteration:
The effect you’re encountering is called closures, when you define a function that references non-local variables, the function retains a reference to the variable, rather than getting its own copy. To illustrate, I’ll expand your code into an equivalent version without comprehensions or lambdas.
So, at this point,
inner_list
has three functions in it, and each function, when called, will return the value ofm
. But the salient point is that they all see the very samem
, even thoughm
is changing, they never look at it until called much later.In particular, since the inner list is constructed completely before the outer list starts getting built,
m
has already reached its last value of 3, and all three functions see that same value.To make the lambdas remember the value of
m
, you could use an argument with a default value:This works because default values are set once, at definition time. Each lambda now uses its own default value of
m
instead of looking form
's value in an outer scope at lambda execution time.Personally, I find this a more elegant solution. Lambda returns a function, so if we want to use the function, then we should use it. It's confusing to use the same symbol for the 'anonymous' variable in the lambda and for the generator, so in my example I use a different symbol to make it hopefully more clear.
it's faster too.
but not as fast as map:
(I ran these tests more than once, result was the same, this was done in python 2.7, results are different in python 3: the two list comprehensions are much closer in performance and both a lot slower, map remains much faster. )