How to decompress the parameter tuple in map function invocation?

Viewed 45

suppose we have a function sum takes two num and return its sum:

def sum(a, b):
    return a + b

and we want to use map to calculate the sum on some iterable container:

map(sum, [(1, 2), (3, 4)])

it will raise an exception:

TypeError: sum() takes exactly 2 arguments (1 given)

What happens here is that sum get invoked on parameter (1, 2) and (3, 4), that gives us an error. We can do that:

sum(*(1, 2)) would correctly return. here is my problem: how could we use the map to pass this tuple into sum gracefully? here is a solution, but not quite as gracefully as what I want:

map(lambda x: sum(*x), [(1, 2), (3, 4)])
1 Answers

That is exactly what starmap is for:

from itertools import starmap

starmap(sum, [(1, 2), (3, 4)])
Related