Search code examples
pythondictionaryiterable-unpacking

Using * idiom to unpack arguments when using map()


Is there a way to unpack a tuple with the * idiom when using the map built-in in Python?

Ideally, I'd like to do the following:

def foo(a, b):
  return a**2 + b

x = [(1,2), (3,4), (5,6)]

results = map(foo, *x)

where results would equal [3, 13, 31]


Solution

  • You're looking for itertools.starmap:

    def foo(a, b):
      return a**2 + b
    
    x = [(1,2), (3,4), (5,6)]
    
    from itertools import starmap
    
    starmap(foo, x)
    Out[3]: <itertools.starmap at 0x7f40a8c99310>
    
    list(starmap(foo, x))
    Out[4]: [3, 13, 31]
    

    Note that even in python 2, starmap returns an iterable that you have to manually consume with something like list.