GeneralBecos GeneralBecos - 6 months ago 18
Python Question

Weird behavior: Lambda inside list comprehension

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?


To make the lambdas remember the value of m, you could use an argument with a default value:

[x() for x in [lambda m=m: m for m in [1,2,3]]]
# [1, 2, 3]

This works because default values are set once, at definition time. Each lambda now uses its own default value of m instead of looking for m's value in an outer scope at lambda execution time.