Open In App

Python | Column summation of tuples

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate
# column summation of list of tuple
# using list comprehension + zip()
 
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + zip()
# column summation of list of tuple
res = [tuple(sum(j) for j in zip(*i))
            for i in zip(*test_list)]
 
# print result
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




# Python3 code to demonstrate
# column summation of list of tuple
# using zip() + map()
 
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using zip() + map()
# column summation of list of tuple
res = [tuple(map(sum, zip(*i)))
      for i in zip(*test_list)]
 
# print result
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)]]
 
# get the length of the inner tuples
n = len(test_list[0][0])
 
# initialize the result list with zeros
res = [(0,)*n for _ in range(len(test_list[0]))]
 
# iterate through the tuples in each list and sum up the elements in each column
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 result
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:

  1. First, the NumPy library is imported using the statement import numpy as np.
  2. A list test_list is defined, which contains two lists of tuples. Each tuple contains two integers.
  3. 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.
  4. 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.
  5. The resulting array is assigned to the variable res.
  6. 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)]]
 
# convert the list to a NumPy array
arr = np.array(test_list)
 
# sum the elements along the first axis (columns)
res = arr.sum(axis=0)
 
# print the result
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:

  1. First, import the reduce() function from the functools module.
  2. Then, initialize the list of tuples test_list.
  3. 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.
  4. 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.
  5. The map() function returns an iterator of tuples. Convert this iterator to a list using the list() function.
  6. Finally, we print the resulting list of tuples.

Python3




# import reduce function from functools module
from functools import reduce
 
# initializing list
test_list = [[(1, 4), (2, 3), (5, 2)],
             [(3, 7), (1, 9), (10, 5)]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using reduce() and lambda function to sum the tuples
res = list(map(lambda x: tuple(reduce(lambda a, b: (a[0] + b[0], a[1] + b[1]), x)), zip(*test_list)))
 
# print result
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.



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads