I want to write a function which returns a list of functions. As a MWE, here's my attempt at function that gives three functions that add 0, 1, and 2 to an input number:
def foo():
result = []
for i in range(3):
temp = lambda x: x + i
print(temp(42)) # prints 42, 43, 44
result.append(temp)
return result
for f in foo():
print(f(42)) #prints 44, 44, 44
Contrary to my expectation, each function ends up using the last value taken by i. I've experienced similar behavior when e.g. a list is used as argument to a function but Python actually uses a pointer to the list, but here i is an integer, so I don't understand what's going on here. I'm running Python 3.5.