Article From:https://segmentfault.com/q/1010000011702170
Question:
def multi():
    return [lambda x: i * x for i in range(4)]


print([m(3) for m in multi()])

Why is this execution result?

Answer 0:

Chi Bangding of closure variables really calculates the value of I when it is called. In fact, it is equivalent to:

def multi():
    r = []
    for i in range(4):
        def f(x):
            return i*x

        r.append(f)
    return r

print([m(3) for m in multi()])

If you want the expected results, you can:

def multi():
    return [lambda x, i=i: i * x for i in range(4)]
print([m(3) for m in multi()])

This is equivalent to:

def multi():
    r = []
    for i in range(4):
        def f(x, i=i):
            return i*x

        r.append(f)
    return r

print([m(3) for m in multi()])

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *