Amazing result with lambdas

I obviously don't understand how lambda works here:

def get_res_lambda():
    res = []
    for v in ['one', 'two', 'three']:
        res.append(lambda: v)
    return res


def get_res():
    res = []
    for v in ['one', 'two', 'three']:
        res.append(v)
    return res

print ">>> With list"
res = get_res()
print(res[0])
print(res[1])
print(res[2])

print ">>> With lambda"
res = get_res_lambda()
print(res[0]())
print(res[1]())
print(res[2]())

I get:

>>> With list
one
two
three
>>> With lambda
three
three
three

I expected:

>>> With list
one
two
three
>>> With lambda
one
two
three

Why does the lambda version always return the last value? What am I doing wrong?

+4
source share
1 answer

Your lambda function returns the value vat the point at which the lambda function runs. The lambda function is executed when you reach print(res[0]()), etc.

By that time, for v in ['one', 'two', 'three']it is already fully completed its cycle and vhas its final value 'three'.

+4
source

Source: https://habr.com/ru/post/1666242/


All Articles