Python | Column summation of tuples
Last Updated : 06 Apr, 2023
Sometimes, we encounter a problem where we deal with a complex type of matrix column summation in which we are given a tuple and we need to perform the summation of its like elements. This has a good application in Machine Learning domain. Let’s discuss certain ways in which this can be done.
Method #1 : Using zip() + list comprehension This problem can be resolved using the list comprehension which could perform the column summation logic and zip function is used to bind the elements as a result and also at the time of vertical summation.
Python3
test_list = [[( 1 , 4 ), ( 2 , 3 ), ( 5 , 2 )], [( 3 , 7 ), ( 1 , 9 ), ( 10 , 5 )]] print ("The original list : " + str (test_list)) res = [ tuple ( sum (j) for j in zip ( * i)) for i in zip ( * test_list)] print ("The summation of columns of tuple list : " + str (res)) |
Output : The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]] The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]
Time complexity: O(nm), where n is the number of sublists in the input list and m is the length of the sublists (assuming that the length of all sublists is the same).
Auxiliary space: O(nm), since it creates a new list of tuples with the same dimensions as the input list.
Method #2 : Using zip() + map() The task of binding the column elements can also be performed using the map function and the zip function performs the task of binding the summation tuples. Both logics bound by list comprehension.
Python3
test_list = [[( 1 , 4 ), ( 2 , 3 ), ( 5 , 2 )], [( 3 , 7 ), ( 1 , 9 ), ( 10 , 5 )]] print ("The original list : " + str (test_list)) res = [ tuple ( map ( sum , zip ( * i))) for i in zip ( * test_list)] print ("The summation of columns of tuple list : " + str (res)) |
Output : The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]] The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]
Time Complexity : O(m*n), where m is the number of rows and n is the number of columns in the list of tuples.
Auxiliary Space : O(n), where n is the number of columns in the list of tuples.
Method #3: Using for loop and append()
Using a for loop and append() method to iterate through the tuples in each list and sum up the elements in each column.
Python3
test_list = [[( 1 , 4 ), ( 2 , 3 ), ( 5 , 2 )], [( 3 , 7 ), ( 1 , 9 ), ( 10 , 5 )]] n = len (test_list[ 0 ][ 0 ]) res = [( 0 ,) * n for _ in range ( len (test_list[ 0 ]))] for l in test_list: for i, tpl in enumerate (l): res[i] = tuple (x + y for x,y in zip (res[i], tpl)) print ( "The summation of columns of tuple list : " , res) |
Output The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]
Time Complexity: O(n^2), where n is the number of elements in the longest inner tuple. This is because the code uses two nested loops to iterate through the tuples in the input list.
Auxiliary Space: O(n), where n is the number of elements in the longest inner tuple. This is because the code creates a new tuple for each column in the input list to store the sum of the elements in that column.
Method #4: Using NumPy library
NumPy is a popular library for numerical computations in Python. It provides many efficient and convenient functions for working with arrays, matrices, and other data structures. We can use the NumPy library to solve the given
step-by-step explanation of the program:
- First, the NumPy library is imported using the statement import numpy as np.
- A list test_list is defined, which contains two lists of tuples. Each tuple contains two integers.
- The list test_list is converted to a NumPy array using the function np.array(). The resulting NumPy array has dimensions 2×3, since there are two lists of tuples, and each list contains three tuples.
- The sum() method of NumPy arrays is used to sum the elements along the first axis (columns) of the array. The resulting array has dimensions 1×3, since there are three columns in the original array.
- The resulting array is assigned to the variable res.
- Finally, the print() function is used to print a string that describes the result. The variable res is included in the string using an f-string, which allows variables to be inserted into strings using curly braces {}.
Python3
import numpy as np test_list = [[( 1 , 4 ), ( 2 , 3 ), ( 5 , 2 )], [( 3 , 7 ), ( 1 , 9 ), ( 10 , 5 )]] arr = np.array(test_list) res = arr. sum (axis = 0 ) print ( "The summation of columns of tuple list : " , res) |
OUTPUT:
The summation of columns of tuple list : [[ 4 11] [ 3 12] [15 7]]
Time complexity: O(n^2), where n is the length of the inner tuples. This is because we need to iterate over all the elements in the input list and perform a constant number of operations (addition) on each element.
Auxiliary space: O(n), where n is the length of the inner tuples. This is because we need to create a new array of zeros to initialize the result, and a new array to store the transposed input. However, these arrays have a fixed size that depends only on the length of the inner tuples, so the space complexity is O(n).
Method 5: Using the built-in function reduce() from the functools module.
Step-by-step approach:
- First, import the reduce() function from the functools module.
- Then, initialize the list of tuples test_list.
- Next, use the zip() function to group the tuples by their index, i.e., all the first tuples will be grouped together, all the second tuples will be grouped together, and so on. We use the * operator to unpack the test_list list and pass it as arguments to the zip() function.
- Use the map() function to apply a lambda function to each group of tuples. The lambda function takes a group of tuples as input and uses the reduce() function to sum the tuples element-wise. The result of each reduce() operation is a tuple of two elements that represent the sums of the corresponding elements of the input tuples. Finally, the lambda function returns this tuple.
- The map() function returns an iterator of tuples. Convert this iterator to a list using the list() function.
- Finally, we print the resulting list of tuples.
Python3
from functools import reduce test_list = [[( 1 , 4 ), ( 2 , 3 ), ( 5 , 2 )], [( 3 , 7 ), ( 1 , 9 ), ( 10 , 5 )]] print ( "The original list : " + str (test_list)) res = list ( map ( lambda x: tuple ( reduce ( lambda a, b: (a[ 0 ] + b[ 0 ], a[ 1 ] + b[ 1 ]), x)), zip ( * test_list))) print ( "The summation of columns of tuple list : " + str (res)) |
Output The original list : [[(1, 4), (2, 3), (5, 2)], [(3, 7), (1, 9), (10, 5)]] The summation of columns of tuple list : [(4, 11), (3, 12), (15, 7)]
Time complexity: O(nm), where n is the number of rows and m is the number of columns in the input list of tuples.
Auxiliary space: O(m), where m is the number of columns in the input list of tuples.
Similar Reads
Python - Tuple Matrix Columns Summation
Sometimes, while working with Tuple Matrix, we can have a problem in which we need to perform summation of each column of tuple matrix, at the element level. This kind of problem can have application in Data Science domains. Let's discuss certain ways in which this task can be performed. Input : tes
8 min read
Python | Summation of tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 min read
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task ca
7 min read
Python - Absolute Tuple Summation
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the summation of absolute values of intermediate tuple elements. This kind of problem can have application in many domains such as web development. Let's discuss certain ways in which this task can be perf
6 min read
Python | Summation of two list of tuples
Sometimes, while working with Python records, we can have a problem in which we need to perform cross-summation of list of tuples. This kind of application is popular in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip
6 min read
Python - Summation of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Letâs discuss certain ways in which this particular problem can be solved. Method #1: Using
4 min read
Python | Grouped summation of tuple list
Many times, we are given a list of tuples and we need to group its keys and perform certain operations while grouping. The most common operation is addition. Let's discuss certain ways in which this task can be performed. Apart from addition, other operations can also be performed by doing small cha
10 min read
Python - Cross tuple summation grouping
Sometimes, while working with Python tuple records, we can have a problem in which we need to perform summation grouping of 1st element of tuple pair w.r.t similar 2nd element of tuple. This kind of problem can have application in day-day programming. Let's discuss certain ways in which this task ca
7 min read
Python - Summation of Unique elements
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its summation. This operations has large no. of applications and hence itâs knowledge is good to have. Method 1 : Naive method + sum() In naive method, we simply t
5 min read
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read