Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 472
user1554752 Avatar asked Mar 29 '26 23:03

user1554752


2 Answers

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.

like image 83
roippi Avatar answered Apr 02 '26 02:04

roippi


An uglier way than the @roippi's way...

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

map(lambda y:y[0]**2 + y[1], x)
like image 32
Mauro Baraldi Avatar answered Apr 02 '26 02:04

Mauro Baraldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!