Let's say I want to create a list of functions programmatically, e.g. I want to create nine functions that, given a number in input, they add it respectively 1, 2, ... 9 and return it.
My take would be to write the following code:
>>> functions = []
>>> for i in range(1,10):
... functions.append(lambda x : x + i)
...
>>> for f in functions:
... print(f(0), end=' ')
However, the ouput is
9 9 9 9 9 9 9 9 9
Instead of the expected
1 2 3 4 5 6 7 8 9
I understand that this has to do with how Python deals with function arguments, i.e. when I create my lambda
, I bound it to the reference of i
, and not to its value.
How can I get around this? Is there a way to force Python to make a copy of i
, instead of passing is reference?