I am trying to create a list of functions(function objects) that print out corresponding items from another list:
strings = ["a", "b", "c"]
functions = []
for i in strings:
functions.append(lambda: print(i))
What the above code does is create lambda functions which when called print the value of i. I want the items of the strings list and the functions list to have a one-to-one relationship, meaning I want the following results.
Output 1:
>>> functions[0]()
'a'
>>> functions[1]()
'b'
>>> functions[2]()
'c'
But I'm getting this:
Output 2:
>>> functions[0]()
'c'
>>> functions[1]()
'c'
>>> functions[2]()
'c'
I know the variable i in the for loop persists after the end of the loop, and all the functions end up printing out the same value of i.
Is there any way to make the functions print out the corresponding values of the strings list, like Output1 above?