I am obviously misunderstanding 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 was expecting:
>>> With list
one
two
three
>>> With lambda
one
two
three
Why is the lambda version returning always the last value? What am I doing wrong?