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
You can do this using the itemgetter
:
from operator import itemgetter
fun_list = []
for i in range(5):
fun_list.append(itemgetter(i))
mylist = range(10)
print([f(mylist) for f in fun_list])
In your case, you are assigning a function to all elements referencing a global i
with the value of i
at the time of the call, which is 4 for all calls. You need some sort of currying.
Same without the itemgetter
:
def indexer(i): return lambda y: y[i]
fun_list = []
for i in range(5):
fun_list.append(indexer(i))
mylist = range(10)
print([f(mylist) for f in fun_list])