I want to use lambdas as functions that return objects. Take a look at lambda x: print(item)
, as it is written, the expected result is that holder[str(item)]
will store a function that returns the current item. But my code shows that it always returns the last item.
Why this happens? And is there a way to pass functions that actually return the item?
items = [1,2,3]
holder = {}
for item in items:
holder[str(item)] = lambda x: print(item)
holder['1'](None)
holder['2'](None)
holder['3'](None)
Output:
3
3
3
Expected behavior would be:
1
2
3