Python `map` and arguments unpacking

Radosław Miernik picture Radosław Miernik · Jun 1, 2013 · Viewed 15k times · Source

I know, that

map(function, arguments)

is equivalent to

for argument in arguments:
    function(argument)

Is it possible to use map function to do the following?

for arg, kwargs in arguments:
    function(arg, **kwargs)

Answer

Martijn Pieters picture Martijn Pieters · Jun 1, 2013

You can with a lambda:

map(lambda a: function(a[0], **a[1]), arguments)

or you could use a generator expression or list comprehension, depending on what you want:

(function(a, **k) for a, k in arguments)
[function(a, **k) for a, k in arguments]

In Python 2, map() returns a list (so the list comprehension is the equivalent), in Python 3, map() is a generator (so the generator expression can replace it).

There is no built-in or standard library method that does this directly; the use case is too specialised.