I tried to achieve something like this
list1 = [lambda x: x+0, lambda x: x+1]
by doing this
list2 = [lambda x: x+n for n in range(2)]
But it doesn't work! (Why not?) How do I create a list of functions programmatically?
I tried to achieve something like this
list1 = [lambda x: x+0, lambda x: x+1]
by doing this
list2 = [lambda x: x+n for n in range(2)]
But it doesn't work! (Why not?) How do I create a list of functions programmatically?
n
is reassigned by the for expression, so after the for expression is completed both will see value of n
being 1.
More typical example of this problem can be visible without list expression:
list3 = []
for n in range(2):
def f(x):
return x + n
list3.append(f)
Here also all created function objects will refer to the same variable n
and it will be assigned value 1 and both function objects will work as lambda x: x + 1
.
You can deal with it by creating additional scope with a variable for each created function:
a = [(lambda n: lambda x: x+n)(n) for n in range(2)]