cool mouse
cool mouse

Reputation: 35

What is the conventional way to compute a sum of list of tuples in Python?

Given a list of tuple-s, what is the conventional way to compute its sum?

We can define sum as a tuple in which every element is the sum of corresponding elements from all tuples in list.

For example, the sum of list [(1, 4), (1, -4), (1, 4)] is (3, 4).

Upvotes: 3

Views: 148

Answers (4)

Mykola Semenov
Mykola Semenov

Reputation: 802

You can use reduce from built-in module functools:

from functools import reduce


l = [(1, 4), (1, -4), (1, 4)]
res = reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), l)

Upvotes: 0

j3r3mias
j3r3mias

Reputation: 371

You can combine the indices of each tuple using zip:

[sum(i) for i in zip(*list)]

Upvotes: 2

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2518

You could do this by help of numpy:

import numpy

tuple(sum(numpy.array(list)))
# (3, 4)

Upvotes: 0

Gabio
Gabio

Reputation: 9484

Try:

data = [(1, 4), (1, -4), (1, 4)]
total_a = total_b = 0
for a,b in data:
    total_a += a
    total_b += b
print((total_a, total_b))

Upvotes: -1

Related Questions