>>> funcs = []
>>> for fruit in [ 'apple', 'orange', 'banana' ]:
... funcs.append(lambda: 'I like ' + fruit)
...
>>> for f in funcs:
... print f()
...
I like banana
I like banana
I like banana
Python's lambda resolves the name of the variable at the time of the call, so it becomes "fruit" (='banana') at the time of execution.
Change lambda:'I like' + fruit
to lambda fruit = fruit:'I like' + fruit
.
I think that it is standard to solve functionally with higher-order functions, but if it is ↑, it is good to go with one-liner. (^ ◇ ^)
>>> funcs = []
>>> for fruit in [ 'apple', 'orange', 'banana' ]:
... funcs.append(lambda fruit=fruit: 'I like ' + fruit)
...
>>> for f in funcs:
... print f()
...
I like apple
I like orange
I like banana
Recommended Posts