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 tupleInput = [(1, 13), (1, 190), (3, 25), (1, 12)]  d = {x:0 for x, _ in Input}  for name, num in Input: d[name] += num  # using mapOutput = list(map(tuple, d.items()))  # printing outputprint(Output)
Output:

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

Method #2: Using defaultdict

 # Python code to sum list of tuples having same first value  # Importingfrom collections import defaultdict  # Initialisation of list of tupleInput = [(2, 190), (1, 13), (1, 12),          (2, 14), (3, 82), (1, 70)]  # Initialisation of defaultdictoutput = defaultdict(int)  for k, v in Input:    output[k] += v  # Printing outputprint(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.

My Personal Notes arrow_drop_up