Skip to content
Related Articles

Related Articles

Python | Get sum of tuples having same first value
  • Last Updated : 14 Feb, 2019

Given a list of tuple, the task is to sum the tuples having same first value.

Examples:

Input: [(1, 13), (2, 190), (3, 82), (1, 12)]
Output: [(1, 25), (2, 190), (3, 82)]

Input: [(1, 13), (1, 190), (3, 25), (1, 12)]
Output: [(1, 215), (3, 25)]

 
Let’s discuss the different ways we can do this task.

Method #1: Using map()




# Python code to get sum of tuples having same first value
  
# Initialisation of list of tuple
Input = [(1, 13), (1, 190), (3, 25), (1, 12)]
  
d = {x:0 for x, _ in Input}
  
for name, num in Input: d[name] += num
  
# using map
Output = list(map(tuple, d.items()))
  
# printing output
print(Output)
Output:



[(1, 215), (3, 25)]

 
Method #2: Using defaultdict




# Python code to sum list of tuples having same first value
  
# Importing
from collections import defaultdict
  
# Initialisation of list of tuple
Input = [(2, 190), (1, 13), (1, 12), 
         (2, 14), (3, 82), (1, 70)]
  
# Initialisation of defaultdict
output = defaultdict(int)
  
for k, v in Input:
    output[k] += v
  
# Printing output
print(list(output.items()))
Output:
[(1, 95), (2, 204), (3, 82)]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :