[ACCEPTED]-How to add with tuples-tuples

Accepted answer
Score: 16

I'd go for

>>> map(sum, zip((1, 2), (3, 4)))
[4, 6]

or, more naturally:

>>> numpy.array((1, 2)) + numpy.array((3, 4))
array([4, 6])

0

Score: 12

Do you want to do element-wise addition, or 5 to append the tuples? By default python 4 does

(1,2)+(3,4) = (1,2,3,4)

You could define your own as:

def myadd(x,y):
     z = []
     for i in range(len(x)):
         z.append(x[i]+y[i])
     return tuple(z)

Also, as 3 @delnan's comment makes it clear, this is 2 better written as

def myadd(xs,ys):
     return tuple(x + y for x, y in izip(xs, ys))

or even more functionally:

myadd = lambda xs,ys: tuple(x + y for x, y in izip(xs, ys))

Then 1 do

if( b < a) return myadd((1,0),foo(a-b,b))
Score: 2
tuple(map(operator.add, a, b))

In contrast to the answer by highBandWidth, this 7 approach requires that the tuples be of 6 the same length in Python 2.7 or earlier, instead 5 raising a TypeError. In Python 3, map is slightly 4 different, so that the result is a tuple 3 of sums with length equal to the shorter 2 of a and b.

If you want the truncation behavior 1 in Python 2, you can replace map with itertools.imap:

tuple(itertools.imap(operator.add, a, b))
Score: 2

If you want + itself to act this way, you 7 could subclass tuple and override the addition:

class mytup(tuple):
    def __add__(self, other):
        if len(self) != len(other):
             return NotImplemented # or raise an error, whatever you prefer
         else:
             return mytup(x+y for x,y in izip(self,other))

The 6 same goes for __sub__, __mul__, __div__, __gt__ (elementwise >) etc. More 5 information on these special operators can 4 be found e.g. here (numeric operations) and here (comparisions)

You can still append 3 tuples by calling the original tuple addition: tuple.__add__(a,b) instead 2 of a+b. Or define an append() function in the new class 1 to do this.

More Related questions