GeneralBecos GeneralBecos - 5 months ago 10
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?

Answer

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.

Comments