Generating functions inside loop with lambda expression in python

前端 未结 6 624
眼角桃花
眼角桃花 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:24

    Nice catch. The lambda in the list comprehension is seeing the same local i every time.

    You can rewrite it as:

    a = []
    for i in range(10):
        a.append(makefun(i))
    
    b = []
    for i in range(10):
        b.append(lambda: i)
    

    with the same result.

提交回复
热议问题