2

I know similar questions have been asked, but I have no idea how to apply it to my problem. I am trying to create a tuple with lambda functions which call an array index.

cons=()
for i in range(5):
    cons = cons + (lambda x: x[i],)

All the functions in the tuple use the latest value of i, instead of the initial value. How do I fix this in this example?

Just for completeness sake, I have solved my problem with the below solution:

def indexi(x,j):
  return(x[j])

def indexii():
    for i in range(5):
        yield(partial(indexi, j=i))

cons=()
for func in indexii():
    cons += (func_,) 
Chris
  • 21
  • 3

0 Answers0