Part of the lambda expression that needs explanation

So I really don’t know how to explain this, so bear with me.

Inside the for loop, I have a lambda expression, but I don’t understand why you need the part i=i.

def makeActions():
    acts = []
    for i in range(5):
        acts.append(lambda x, i=i: x**i)
    return acts
+4
source share
1 answer

Let your lambda function break. This is a function that takes two arguments (x, i) and executes x in terms of power i.

The for loop CREATES a new lambda function at each iteration. If you delete i=i, all functions will be the same:lambda x, i: x**i

Thus, there is no value for the for loop. They are all the same.

i=i i for .

[lambda x, i=1: x**i, lambda x, i=2: x**o, lambda ..]

- i.


, , , for, i. , lambda ( i), for . @Arndt , lambda x, y=i: x**y, .

+2

Source: https://habr.com/ru/post/1695390/


All Articles