Issue
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
Solution
You could use partial()
instead of using lambda:
from functools import partial
items = [1,2,3]
holder = {}
for item in items:
holder[str(item)] = partial(print, item)
holder['1'](None)
holder['2'](None)
holder['3'](None)
Giving an output of:
1 None
2 None
3 None
Answered By - Martin Evans
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.