tags:

views:

1466

answers:

7

Is there anyway to get tuples operation in python to work like this:

>>>a = (1,2,3)
>>>b = (3,2,1)
>>>a + b
(4,4,4)

instead of:

>>>a = (1,2,3)
>>>b = (3,2,1)
>>>a + b
(1,2,3,3,2,1)

I know it works like that because the __add__ and __mul__ methods are defined to work like that. So the only way would be to redefine them?

+12  A: 
import operator
tuple(map(operator.add, a, b))
ironfroggy
just recast to a tuple...
daniel
I'd say this is the most pythonic solution.
Matthew Schinckel
+2  A: 

Yes. But you can't redefine built-in types. You have to subclass them:

class MyTuple(tuple):
    def __add__(self, other):
         if len(self) != len(other):
             raise ValueError("tuple lengths don't match")
         return MyTuple(x + y for (x, y) in zip(self, other))
Doug
but then you can't use the tuple syntax.
toby
+8  A: 

Sort of combined the first two answers, with a tweak to ironfroggy's code so that it returns a tuple:

import operator

class stuple(tuple):
    def __add__(self, other):
        return self.__class__(map(operator.add, self, other))
        # obviously leaving out checking lengths

>>> a = stuple([1,2,3])
>>> b = stuple([3,2,1])
>>> a + b
(4, 4, 4)

Note: using self.__class__ instead of stuple to ease subclassing.

Dana
Doesn't it make more sense for __add__ to return stuple(...)?
Roger Pate
Changed it to stuple()
S.Lott
Ah, yeah, thanks guys :)
Dana
+3  A: 

What others have said so far is correct, but if you're more generally interested in vectorizing your code, you might want to check out NumPy arrays.

RexE
+2  A: 
map(sum,zip(a,b))
Triptych
+2  A: 
Mike
+1  A: 

simple solution without class definition that returns tuple

import operator
tuple(map(operator.add,a,b))
DemonEye