News for hackers. Stuff that matters.
Re:WTFPython – Understanding Python through surprising snippets by faizshah on Monday December 23, 2019 @10:53AM (#21864380)
This situation is mentioned in the docs:

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...

Re:WTFPython – Understanding Python through surprising snippets by wvenable on Monday December 23, 2019 @04:46PM (#21867726)
Any feature that is a "great argument for unit testing" is a poor feature.
Re:WTFPython – Understanding Python through surprising snippets by pc86 on Monday December 23, 2019 @03:39PM (#21867156)
Isn't there something wrong if you have to explicitly state i=i?