+ 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))
3 Answers
+ 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
+ 4
So for the example above:
This happens because "i" is not local to the lambdas, but is defined in the outer scope.
+ 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))