+ 5

The different functions produced by list comprehension give the same result!!! Why???

So the following code gives the same result for each function of three namely the result of third function is the same for each other!!! Why does it happen??? L = [lambda x: i*x for i in (7,8,9)] print(L[0](1)) print(L[1](1)) print(L[2](1))

30th Sep 2021, 1:47 PM
Alexander Sergeev
Alexander Sergeev - avatar
3 Antworten
+ 7
It's about scope. From the docs: "This happens because x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined." https://docs.python.org/3.4/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
30th Sep 2021, 4:11 PM
Lisa
Lisa - avatar
+ 4
So for the example above: This happens because "i" is not local to the lambdas, but is defined in the outer scope.
30th Sep 2021, 4:23 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 3
Thanks, Lisa!!! Based on your answer the next code will do what we want for it to do. L = [lambda x, j=i: x*j for i in (7,8,9)] print(L[0](1)) print(L[1](1)) print(L[2](1))
30th Sep 2021, 4:58 PM
Alexander Sergeev
Alexander Sergeev - avatar