Generating functions inside loop with lambda expression in python

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

    One set of functions (a) operates on the argument passed and the other (b) operates on a global variable which is then set to 9. Check the disassembly:

    >>> import dis
    >>> dis.dis(a[2])
      1           0 LOAD_DEREF               0 (i)
                  3 RETURN_VALUE
    >>> dis.dis(b[2])
      1           0 LOAD_GLOBAL              0 (i)
                  3 RETURN_VALUE
    >>>
    

提交回复
热议问题