Python `map` and arguments unpacking Python `map` and arguments unpacking python python

Python `map` and arguments unpacking


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.


For the case of positional arguments only, you can use itertools.starmap(fun, args):

Return an iterator whose values are returned from the function evaluated with a argument tuple taken from the given sequence.

Example:

from itertools import starmapdef f(i, arg):    print(arg * (i+1))for _ in starmap(f, enumerate(["a", "b", "c"])):    pass

prints:

abbccc


You just have to remember that map will pass the arguments to the function as one tuple rather than separate arguments. If you can't change your original function, you can call it with a helper function:

def f(tup):    args, kwargs = tup    function(args, **kwargs)map(f, arguments)