Weird behavior: Lambda inside list comprehension [duplicate]

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.

Leave a Comment