3 ms·
This situation is mentioned in the docs: https://docs.python.org/3.8/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the
by faizshah 7y ago
This situation is mentioned in the docs:
https://docs.python.org/3.8/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result https://docs.python.org/3.8/faq/programming.html#why-do-lamb...
"This happens because i 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. At the end of the loop, the value of i is 4, so all the functions now return 42, i.e. 16."
These sort of scoping gotchas are pretty common across all programming languages and are a great argument for unit testing. As usual the answer is be more explicit what you're asking the language to do:
>>> powers_of_x = [lambda x, i=i: x*i for i in range(10)]
>>> [f(2) for f in powers_of_x]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Note the positional argument with default "i=i."
More discussion:
https://stackoverflow.com/questions/452610/how-do-i-create-a-list-of-python-lambdas-in-a-list-comprehension-for-loop https://stackoverflow.com/questions/452610/how-do-i-create-a...