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?
source
share