
- 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
Grouped summation of tuple list in Python
When it is required to find the grouped summation of a list of tuple, the 'Counter' method and the '+' operator need to be used.
The 'Counter' is a sub-class that helps count hashable objects, i.e it creates a hash table on its own (of an iterable- like a list, tuple, and so on) when it is invoked.
It returns an itertool for all of the elements with a non-zero value as the count.
The '+' operator can be used to add numeric values or concatenate strings.
Below is a demonstration for the same −
Example
from collections import Counter my_list_1 = [('Hi', 14), ('there', 16), ('Jane', 28)] my_list_2 = [('Jane', 12), ('Hi', 4), ('there', 21)] print("The first list is : ") print(my_list_1) print("The second list is : " ) print(my_list_2) cumulative_val_1 = Counter(dict(my_list_1)) cumulative_val_2 = Counter(dict(my_list_2)) cumulative_val_3 = cumulative_val_1 + cumulative_val_2 my_result = list(cumulative_val_3.items()) print("The grouped summation of list of tuple is : ") print(my_result)
Output
The first list is : [('Hi', 14), ('there', 16), ('Jane', 28)] The second list is : [('Jane', 12), ('Hi', 4), ('there', 21)] The grouped summation of list of tuple is : [('Hi', 18), ('there', 37), ('Jane', 40)]
Explanation
- The required packages are imported.
- Two list of tuples are defined, and are displayed on the console.
- Both of these list of tuples are converted to dictionaries.
- They are added using the '+' operator.
- This result is converted to a list, by using only the 'values' of the dictionary.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.
- Related Articles
- Python Grouped summation of tuple list¶
- Summation of list as tuple attribute in Python
- Python – Dual Tuple Alternate summation
- Summation of tuples in list in Python
- Python Grouped Flattening of list
- 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?
- Dictionary to list of tuple conversion in Python
- Python – Cross Pairing in Tuple List
- Maximum element in tuple list in Python
- Convert a list into tuple of lists in Python
- Python - Column summation of tuples
- Python - Join tuple elements in a list
- List vs tuple vs dictionary in Python

Advertisements