Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python element-wise tuple operations like sum

Tags:

python

tuples

People also ask

How do you sum all the elements of a tuple in Python?

How to find a sum of a tuple in Python. To find a sum of the tuple in Python, use the sum() method. Define a tuple with number values and pass the tuple as a parameter to the sum() function; in return, you will get the sum of tuple items.

Can sum be used in tuple?

A list of tuple basically contains tuples enclosed in a list. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result. The 'sum' method can be used to add the elements in an iterable.


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

Using all built-ins..

tuple(map(sum, zip(a, b)))

This solution doesn't require an import:

tuple(map(lambda x, y: x + y, tuple1, tuple2))

from numpy import array

a = array( [1,2,3] )
b = array( [3,2,1] )

print a + b

gives array([4,4,4]).

See http://www.scipy.org/Tentative_NumPy_Tutorial


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.