I was wondering whether for most examples it is more ‘pythonic’ to use lambda or the partial function?
For example, I might want to apply imap on some list, like add 3 to every element using:
imap(lambda x : x + 3, my_list)
Or to use partial:
imap(partial(operator.add, 3), my_list)
I realize in this example a loop could probably accomplish it easier, but I’m thinking about more non-trivial examples.
In Haskell, I would easily choose partial application in the above example, but I’m not sure for Python. To me, the lambda seems the the better choice, but I don’t know what the prevailing choice is for most python programmers.
To be truly equivalent to
imap, use a generator expression:Like
imap, this doesn’t immediately construct an entire new list, but instead computes elements of the resulting sequence on-demand (and is thus much more efficient than a list comprehension if you’re chaining the result into another iteration).If you’re curious about where
partialwould be a better option thanlambdain the real world, it tends to be when you’re dealing with variable numbers of arguments:The equivalent version using
lambdawould be…which is slightly less concise – but
lambdadoes give you the option of out-of-order application, whichpartialdoes not: