Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outer scope variable in lambda function [duplicate]

Why in python

[f() for f in [lambda: d for d in [1,2]]]

gives

[2, 2]

Why result differ from another languages (where result is [1,2] as expected)? There are some reasonable reasons for such non-obvious behavior?

like image 930
kakabomba Avatar asked Apr 07 '26 06:04

kakabomba


1 Answers

In this [lambda d: for d in [1,2]] what you have is

"Running d from 1 to 2, give me a function returning the value of d at the moment when the function is called."

After that list of two functions is constructed, you call [f() for f in that list]. At the moment the function is called, d in [1,2] has already completed, and d has its final value, 2. So both functions return 2.

One way to get a different result is to copy d to a variable for each lambda function you create. The easiest way to do that is:

[f() for f in [lambda x=d: x for d in [1,2]]]

Here each lambda has its own default value for x, which is d at the time the function is created.

like image 164
khelwood Avatar answered Apr 08 '26 21:04

khelwood