I'm sure there's a way of doing this, but I haven't been able to find it. Say I have:
foo = [
[1, 2],
[3, 4],
[5, 6]
]
def add(num1, num2):
return num1 + num2
Then how can I use map(add, foo)
such that it passes num1=1
, num2=2
for the first iteration, i.e., it does add(1, 2)
, then add(3, 4)
for the second, etc.?
- Trying
map(add, foo)
obviously doesadd([1, 2], #nothing)
for the first iteration - Trying
map(add, *foo)
doesadd(1, 3, 5)
for the first iteration
I want something like map(add, foo)
to do add(1, 2)
on the first iteration.
Expected output: [3, 7, 11]
There was another answer with a perfectly valid method (even if not as readable as ajcr's answer), but for some reason it was deleted. I'm going to reproduce it, as it may be useful for certain situations
It sounds like you need
starmap
:This unpacks each argument
[a, b]
from the listfoo
for you, passing them to the functionadd
. As with all the tools in theitertools
module, it returns an iterator which you can consume with thelist
built-in function.From the documents:
try this: