I understand functional programming well. I want to create a list of functions that each selects a different element of a list. I have reduced my problem to a simple example
Surely this is a Python bug...
This is a misunderstanding of scopes. Since all five instances of fun()
are defined in the same scope, they will all have the same value of all names in that scope, including i
. In order to fix this you need to separate the value used from the scope containing the loop itself. This can be done by defining the function within a completely different scope.
fun_list = []
def retfun(i):
def fun(e):
return e[i]
return fun
for i in range(5):
fun_list.append(retfun(i))
mylist = range(10)
print([f(mylist) for f in fun_list])