alvas
alvas

Reputation: 122330

How to add elements individually in tuple?

How to add elements individually within the tuple?

For example, i need (2, 4) from (0,1) + (2,3), I've been doing it as such but is there a more pythonic / less verbose way to do the same?

>>> x = (0,1)
>>> y = (2,3)
>>> x + y
(0, 1, 2, 3)
>>> tuple(i+j for i,j in zip(x,y))
(2, 4)

Upvotes: 1

Views: 182

Answers (3)

Yi Xiang Chong
Yi Xiang Chong

Reputation: 774

This might be a faster way to add individual elements from tuples using numpy:

import numpy as np 

x = (0,1)
y = (2,3)

z = np.array(x) + np.array(y)
z = tuple(z)

z
(2, 4)

Upvotes: 0

James Mills
James Mills

Reputation: 19050

You can use zip and sum here:

Example:

>>> x = (0, 1)
>>> y = (2, 3)
>>> tuple(map(sum, zip(x, y)))
(2, 4)
  • zip lets us combine elements of two iterables or lists in pairs.
  • sum lets us sum the pairs
  • map lets us apply the sum function per pair.
  • finally we convert the resulting list (or iterable in Python 3.x) back into a tuple since that's what you seem to have wanted.

The above example basically ends up being;

(0 + 2, 1 + 3)

Upvotes: 3

shx2
shx2

Reputation: 64378

Your own solution is the correct way to do that in pure python.

If you'd like to avoid the loop, you can vectorize the operation using numpy:

import numpy as np
tuple( np.asarray(tup1) + np.asarray(tup2) )

You should only convet the data back to a tuple if you really need it as a tuple. Otherwise, leave is as a numpy array, which means you can apply more vectorized operations to it later.

Also, the second conversion to np.asarray is optional. The first one would suffice (the other conversions are automatically done by numpy).

Upvotes: 2

Related Questions