Say I want to create a list of 5 functions, where the i-th function just adds i to the argument. The naive code
L = []
for i in range(5):
def f(z):
return z+i
L.append(f)
apparently does not work: print([f(0) for f in L])
yields [4, 4, 4, 4, 4]
. Similarly,
L = [lambda z: z+i for i in range(5)]
does not work either. The value of i at the time when the function is defined is not fixed to f. A clumsy hack is
tmp = ["lambda z:z+{}".format(i) for i in range(5)]
L = eval("[" + ",".join(tmp) + "]")
But I'm sure that there is a clean solution! Which is it?