Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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)

Solution 2:

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).

Solution 3:

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)

Post a Comment for "How To Add Elements Individually In Tuple?"