7

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.

Peter Smit
  • 27,696
  • 33
  • 111
  • 170
  • 3
    A duplicate of a question asked a year and a half ago which didn't receive any good answers seems fine. All of the answers in that are map-based, which is much less clean than a list comprehension/generation expression (below). The accepted answer in that one is much worse--overriding a class just to perform a method on it makes no sense at all. – Glenn Maynard Sep 27 '10 at 10:17
  • I suppose the reason for the accepted answer in that one is because that's the particular weird behavior the question asked for, so it's not really the answerer's fault. – Glenn Maynard Sep 27 '10 at 10:23

4 Answers4

15
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
  • 72,339
  • 21
  • 134
  • 141
  • The list comprehension is usually preferable. This is far more immediately intuitive than all of the functional answers in #497885. – Glenn Maynard Sep 27 '10 at 10:13
  • @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 Sep 27 '10 at 10:15
  • 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 Sep 27 '10 at 10:19
6

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
  • 10,094
  • 2
  • 35
  • 33
4
>>> t1 = (0,-1,7)
>>> t2 = (3,4,-7)
>>> tuple(i + j for i, j in zip(t1, t2))
(3, 3, 0)
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
3

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
  • 82,968
  • 29
  • 138
  • 152