
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Grouped summation of tuple list¶
In this tutorial, we are going to write a program that adds all the values with the same keys different lists. Let's see an example to understand it clearly.
Input
list_one = [('a', 2), ('b', 3), ('c', 5)] list_two = [('c', 7), ('a', 4), ('b', 2)]
Output
[('a', 6), ('b', 5), ('c', 12)]
Follow the given steps to solve the problem.
- Initialize the lists.
- Convert the first list into dictionary using dict and store it in a variable.
- Iterate over the second list and add the corresponding value to the key present in the dictionary.
- Print the result.
Example
# initializing the lists list_one = [('a', 2), ('b', 3), ('c', 5)] list_two = [('c', 7), ('a', 4), ('b', 2)] # convering list_one to dict result = dict(list_one) # iterating over the second list for tup in list_two: # checking for the key in dict if tup[0] in result: result[tup[0]] = result.get(tup[0]) + tup[1] # printing the result as list of tuples print(list(result.items()))
Output
If you run the above code, then you will get the following result.
[('a', 6), ('b', 5), ('c', 12)]
We can solve the above problem without iterating over any list using Counter from collections. Let's see it.
Example
# importing the Counter from collections import Counter # initializing the lists list_one = [('a', 2), ('b', 3), ('c', 5)] list_two = [('c', 7), ('a', 4), ('b', 2)] # getting the result result = Counter(dict(list_one)) + Counter(dict()) # printing the result as list of tuples print(list(result.items()))
Output
If you run the above code, then you will get the following result.
[('a', 6), ('b', 5), ('c', 12)]
Conclusion
If you have any doubts regarding the tutorial, mention them in the comment section.
- Related Articles
- Grouped summation of tuple list in Python
- Summation of list as tuple attribute in Python
- Python – Dual Tuple Alternate summation
- Python Grouped Flattening of list
- Summation of tuples in list in Python
- Alternate element summation in list (Python)
- Flatten tuple of List to tuple in Python
- Why python returns tuple in list instead of list in list?
- Python - Column summation of tuples
- Python - Ways to iterate tuple list of lists
- Dictionary to list of tuple conversion in Python
- Extract digits from Tuple list Python
- Python – Cross Pairing in Tuple List
- Python – Summation of consecutive elements power
- Python program to Flatten Nested List to Tuple List

Advertisements