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_,) 
2
  • 3
    Possibly duplicate, see stackoverflow.com/questions/21053988/… Commented Aug 4, 2015 at 14:33
  • 1
    Not an answer to your question but you could use operator.itemgetter instead of the lambda function Commented Aug 4, 2015 at 14:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.