Python · Understanding of [lambda x: x*i for i in range(4)]

topic

lst = [lambda x: x*i for i in range(4)]
res = [m(2) for m in lst]
print res

This question involves Python 's knowledge of closures and delayed binding (Python scope).

In core Python programming, closures are defined as follows:

If inside an inner function, there is a reference to a variable in the outer scope (but not in the global scope), then the inner function is considered a closure.

It can be summed up in three points:

1, is an inline function

2. Reference to external function variables

3. External functions return embedded functions

Simple closure example:

def counter(start_at=0):
    count = [start_at]
    def incr():
        count[0] += 1
        return count[0]
    return incr

The above question can be written as:

def func():
    fun_list = []
    for 

Guess you like

Origin blog.csdn.net/qq_37865996/article/details/124311407