Python element-wise tuple operations like sum

Rodrigo picture Rodrigo · Jan 31, 2009 · Viewed 125.8k times · Source

Is there anyway to get tuple operations 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?

Answer

ironfroggy picture ironfroggy · Jan 31, 2009
import operator
tuple(map(operator.add, a, b))