Python | Summation of tuples in list

Sometimes, while working with records, we can have a problem in which we need to find the cummulative sum of all the values that are present in tuples. This can have application in cases in which we deal with a lot of records data. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using sum() + map()
Combination of above functions can be used to solve this particular problem. In this the task of summation is performed by sum(), and applying the summation functionality to each element in tuple list is performed by map().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Summation of tuples in list
# using sum() + map()
  
# initialize list of tuple
test_list = [(1, 3), (5, 6, 7), (2, 6)]
  
# printing original tuples list
print("The original list : " + str(test_list))
  
# Summation of tuples in list
# using sum() + map()
res = sum(map(sum, test_list))
  
# printing result
print("The summation of all tuple elements are : " + str(res))

chevron_right


Output :



The original list : [(1, 3), (5, 6, 7), (2, 6)]
The summation of all tuple elements are : 30

 

Method #2 : Using sum() + izip()
The combination of above functions can be used to perform this particular task. In this, we perform the task of map() using izip(). It helps to club all the elements for summation by sum(). Works only for single element tuple and only with Python2.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Summation of tuples in list
# using sum() + izip()
from itertools import izip
  
# initialize list of tuple
test_list = [(1, ), (5, ), (2, )]
  
# printing original tuples list
print("The original list : " + str(test_list))
  
# Summation of tuples in list
# using sum() + map()
res = sum(*izip(*test_list))
  
# printing result
print("The summation of all tuple elements are : " + str(res))

chevron_right


Output :

The original list : [(1, ), (5, ), (2, )]
The summation of all tuple elements are : 8


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.