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.
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.
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.
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.
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
.
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))))
>>> t1 = (0,-1,7)
>>> t2 = (3,4,-7)
>>> tuple(i + j for i, j in zip(t1, t2))
(3, 3, 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With