Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets []
Example:
list = [3 ,1, 5, 7]
Now, let's get back to our topic of cross tuple summation.
Cross Tuple Summation Grouping in Python
While creating complex applications we need to manipulate data structures a lot, one of which is a cross-collection summation in which we perform cross summation of collections based on the sum condition element.
Cross Tuple summation grouping is performing summation operation between tuples using a specific element of the tuple which in this problem is the 2nd element of the tuple. So, we will be adding the first elements of all tuples of the list whose second element is the same.
Input:
tupList = [(2, 3), (9, 3), (1, 5), (2, 8)]
Output:
[(11, 3), (1, 5), (2, 8)]
For solving such problems, python provides multiple ways and methods.
Method 1:
A direct method to solve the problem is by traversing the list and checking tuples with the same second element and performing addition based on it.
Output:
Method 2:
An Alternative method to solve the problem is by performing summation using sum() method along with list comprehension and checking for tuples with the same second value using groupby() method. Then create the list by using zip() method.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer