I’m a little confusing when try something like this
b = [lambda x:x**i for i in range(11)]
When I then try b[1](2) I have 1024 as a result that is wrong. But when I write so
b = [(lambda i: lambda x:x**i)(i) for i in range(11)]
all is OK
>>> b[1](2)
2
>>> b[5](2)
32
It works fine but what’s wrong in first code?
This is due to how closures in Python work.
The loop changes the value in the scope that all the functions share. Move generation of the function into a separate scope, i.e. function.