Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pairwise sum two equal-length tuples [duplicate]

Tags:

python

tuples

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.

like image 877
Peter Smit Avatar asked Sep 27 '10 10:09

Peter Smit


People also ask

How do you add two tuples together?

When it is required to concatenate multiple tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements.

How do you sum a list of tuples in Python?

To find a sum of the tuple in Python, use the sum() method. Define a tuple with number values and pass the tuple as a parameter to the sum() function; in return, you will get the sum of tuple items.

How do you copy a tuple in Python?

Method #1 : Using * operator The multiplication operator can be used to construct the duplicates of a container. This also can be extended to tuples even though tuples are immutable.


3 Answers

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.

like image 105
Manoj Govindan Avatar answered Sep 18 '22 14:09

Manoj Govindan


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))))
like image 24
pillmuncher Avatar answered Sep 21 '22 14:09

pillmuncher


>>> t1 = (0,-1,7)
>>> t2 = (3,4,-7)
>>> tuple(i + j for i, j in zip(t1, t2))
(3, 3, 0)
like image 40
SilentGhost Avatar answered Sep 20 '22 14:09

SilentGhost