3 ms·
In the particular case of constructing several similar functions that do essentially the same thing, lambda is a rather natural choice. Being more explicit and
by nine_k 13y ago
In the particular case of constructing several similar functions that do essentially the same thing, lambda is a rather natural choice.
Being more explicit and less hacky can well be combined with staying true to functional style:
from functools import partial
mul = lambda x, y: x*y # could use int.__mul__, too
multipliers = [partial(mul, n) for n in range(5)]
It does the closure-capturing of n for you.
- maxerickson 13y agoA function defined with def would work just the same there. It would have a big ugly 'return' in it and be a few characters longer, but it would work the same, so I don't see what lambda brings to it.
- nine_k 13y agoBoth def and lambda would fail identically in this context.