Generating functions inside loop with lambda expression in python

前端 未结 6 610
眼角桃花
眼角桃花 2020-11-30 08:37

If I make two lists of functions:

def makeFun(i):
    return lambda: i

a = [makeFun(i) for i in range(10)]
b = [lambda: i for i in range(10)]
6条回答
  •  离开以前
    2020-11-30 09:13

    Technically, the lambda expression is closed over the i that's visible in the global scope, which is last set to 9. It's the same i being referred to in all 10 lambdas. For example,

    i = 13
    print b[3]()
    

    In the makeFun function, the lambda closes on the i that's defined when the function is invoked. Those are ten different is.

提交回复
热议问题