Python create function in a loop capturing the loop variable

后端 未结 5 1408
無奈伤痛
無奈伤痛 2020-12-05 03:38

What\'s going on here? I\'m trying to create a list of functions:

def f(a,b):
    return a*b

funcs = []

for i in range(0,10):
    funcs.append(lambda x:f(         


        
5条回答
  •  醉酒成梦
    2020-12-05 04:05

    Considering the final value of i == 9

    Like any good python function, it's going to use the value of the variable in the scope it was defined. Perhaps lambda: varname (being that it is a language construct) binds to the name, not the value, and evaluates that name at runtime?

    Similar to:

    i = 9
    def foo():
        print i
    
    i = 10
    foo()
    

    I'd be quite interested in finding out of my answer is correct

提交回复
热议问题