Summation of tuples in list in Python

PythonServer Side ProgrammingProgramming

When it is required to sum the elements present in a list of tuple, the 'map' method and the 'sum' method can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

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.

Below is a demonstration of the same −

Example

Live Demo

my_list = [(11, 14), (54, 56), (98, 0), (13, 76)]

print("The list is : ")
print(my_list)

my_result = sum(map(sum, my_list))

print("The summation of tuples in a list is: ")
print(my_result)

Output

The list is :
[(11, 14), (54, 56), (98, 0), (13, 76)]
The summation of tuples in a list is:
322

Explanation

  • A list of tuple is defined, and is displayed on the console
  • The iterable is mapped to the 'sum' and all the elements are summed.
  • This would again be used as parameter to 'sum' method, which gives the final result.
  • This is assigned to a value.
  • It is displayed on the console.
raja
Published on 12-Mar-2021 05:42:40
Advertisements