I encountered a problem when I tried to created a list of functions, using lambda function. The idea is to create a function next down to the list based on the function previously created in the list. It seems that if I use index in the definition of the function, the index is not a fixed number inside the function, although the index is already assigned a value.
Here is an example of code:
lt=[1,2,3]
ff=[0]*3
for i in range (3):
print (i)
if (i==0) :
ff[i]=lambda x : 20*x
if (i==1) :
ff[i]=lambda x : ff[0](x)+x*lt[i]
print (ff[i](3))
if (i==2):
print (ff[0](3))
print (ff[1](3))
ff[i]=lambda x : x**3
print (ff[i](3))
I got answers like:
0
1
66
2
60
69
27
I thought I should have ff1 as 66 when the function is called at the 2nd time. However, I got 69. It seems the function was called with i=2, although the function ff[1] was set with i=1. I don't know if this is considered a bug, or just I misunderstand the way lambda function is used when creating it in a list. Can anyone help me on this, or provide an alternative solution? Thanks!
(update: Sorry, the code was posted with a mistake originally. The code is updated)
You could create an enclosure around your lambda
to hold the value you want for i
:
ff[i]=(lambda fi: lambda x : ff[0](x)+x*lt[fi])(i)
Or you could add a parameter to your lambda w/ i
as the default value:
ff[i]=lambda x,fi=i : ff[0](x)+x*lt[fi]