tags:

views:

126

answers:

4

How can I get the pairwise sum of two equal length tuples? For example if I have (0,-1,7) and (3,4,-7) I would like to have (3,3,0) as answer.

+10  A: 
tuple(map(lambda (x, y): x + y, zip((0,-1,7), (3,4,-7))))

If you prefer to avoid map and lambda then you can do:

tuple(x + y for x,y in zip((0,-1,7), (3,4,-7)))

EDIT: As one of the answers pointed out, you can use sum instead of explicitly splitting the tuples returned by zip. Therefore you can rewrite the above code sample as shown below:

tuple(sum(t) for t in zip((0,-1,7), (3,4,-7)))

Reference: zip, map, sum.

Manoj Govindan
The list comprehension is usually preferable. This is far more immediately intuitive than all of the functional answers in #497885.
Glenn Maynard
@Glenn: agreed. That said somehow I find it easier to first think in terms of map and filter and then map it (no pun intended :P) to a list comprehension.
Manoj Govindan
I'm the other way around: list comprehensions (in this case, generator expressions, actually) are naturally intuitive to me, but I have to think about map--probably because it's much less frequently used in Python.
Glenn Maynard
+2  A: 
>>> t1 = (0,-1,7)
>>> t2 = (3,4,-7)
>>> tuple(i + j for i, j in zip(t1, t2))
(3, 3, 0)
SilentGhost
+1  A: 

Alternatively (good if you have very big tuples or you plan to do other mathematical operations with them):

> import numpy as np
> t1 = (0, -1, 7)
> t2 = (3, 4, -7)
> at1 = np.array(t1)
> at2 = np.array(t2)
> tuple(at1 + at2)
(3, 3, 0)

Cons: more data preparation is needed. Could be overkill in most cases.

Pros: operations are very explicit and isolated. Probably very fast with big tuples.

joaquin
+4  A: 

Use sum():

>>> tuple(sum(pair) for pair in zip((0,-1,7), (3,4,-7)))

or

>>> tuple(map(sum, zip((0,-1,7), (3,4,-7))))
pillmuncher