Search code examples
pythonlistsumtuples

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).


Solution

  • 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))