Why are my lambdas not working?

I struggle to do lambda work. Here is some sample code, but it shows my problem well.

lambdas = list() for i in range(5): lambdas.append(lambda x:i*i*x) print lambdas[0](1) print lambdas[2](1) 

This will give me 16, but I expect that I will have a different value for different lambdas. Why is this happening!

+7
python
source share
2 answers

In this code:

 for i in range(5): lambdas.append(lambda x:i*i*x) 

The value of i determined when the function starts. The value of i , when the function is defined, is lost.

Use instead:

 lambdas = list() for i in range(5): lambdas.append(lambda x, i=i : i*i*x) print lambdas[0](1) print lambdas[2](1) 

This gives:

 0 4 

This works because, as a special case, the default arguments for the function, as in i=i above, are immediately bound.

+9
source share

i 4 when your loop ends so i is 4 for each lambda .

If you type i outside the loop, you will see that it is 4:

 for i in range(5): lambdas.append(lambda x: i * i * x) print(i) 4 

You use a variable that is updated throughout the loop, if you call a lambda inside the loop, you will get what you expect.

 for i in range(5): lambdas.append(lambda x: i * i * x) print(lambda x: i * i * x)(1) 0 1 4 9 16 

Behavior is what you expect, i is just a variable, like any other.

On a side note, you can use the comp list to create your list:

 lambdas = [lambda x,i=i: i * i * x for i in xrange(5)] 
+6
source share

All Articles