Open In App
Related Articles

Python – Summation Matrix columns

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Sometimes, we are encountered with such problem in which we need to find the sum of each column in a matrix i.e sum of each index in list of lists. This kind of problem is quite common and useful in competitive programming. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using sum() + list comprehension + zip()

The combination of the above methods are required to solve this particular problem. The sum function is used to get the required sum value and zip function provides the combination of like indices and then list is created using list comprehension.

Python3

# Python3 code to demonstrate
# Summation of each column in Matrix
# using sum() + list comprehension + zip()
 
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using sum() + list comprehension + zip()
# Summation of each column in Matrix
res = [sum(idx) for idx in zip(*test_list)]
 
# print result
print("The Summation of each index list is : " + str(res))

                    

Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]

Time complexity of this code is O(N*M) where N is the number of rows and M is the number of columns in the matrix. The reason for this is that the code is iterating through each element of the matrix, which requires N * M operations.
Auxiliary space used in this code is O(n), where n is the number of columns in the matrix. This is because the code uses a list comprehension, to sum up each column, which requires O(n) space to store the intermediate results.

Method #2: Using map() + sum() + zip() 

This works in almost similar way as the above method, but the difference is just that we use map function to build the sum list rather than using list comprehension. 

Python3

# Python3 code to demonstrate
# Summation of each column in Matrix
# using map() + sum() + zip()
 
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using map() + sum() + zip()
# Summation of each column in Matrix
res = list(map(sum, zip(*test_list)))
 
# print result
print("The Summation of each index list is : " + str(res))

                    
Output : 
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]

Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(m), where m is the number of columns in the matrix.

Method #3: Using for loops

Python3

# Python3 code to demonstrate
# Summation of each column in Matrix
 
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# Summation of each column in Matrix
res=[]
for i in range(0,len(test_list)):
    s=0
    for j in range(0,len(test_list)):
        s+=test_list[j][i]
    res.append(s)
         
# print result
print("The Summation of each index list is : " + str(res))

                    

Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]

Time Complexity : O(N*N)
Auxiliary Space : O(N)

Method 4: Using the numpy library.

Step-by-step approach:

  • Install and import the numpy library
  • Convert the list to a numpy array
  • Use the np.sum() function with the axis parameter set to 0 to get the column-wise sum
  • Convert the numpy array back to a list using the tolist() function
  • Print the result

Below is the implementation of the above approach:

Python3

import numpy as np
 
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# Convert the list to a numpy array
np_array = np.array(test_list)
 
# Use the np.sum() function with the axis parameter set to 0 to get the column-wise sum
res = np.sum(np_array, axis=0)
 
# Convert the numpy array back to a list using the tolist() function
res_list = res.tolist()
 
# print result
print("The Summation of each index list is : " + str(res_list))

                    

Output:

The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]

Time complexity: O(n^2) since we have to iterate through each element of the matrix.
Auxiliary space: O(n^2) since we have to create a numpy array to store the matrix elements.

Method 5 : Using the built-in function functools.reduce()

  1. Import the reduce() function from the functools module.
  2. Initialize the input matrix test_list.
  3. Print the original input matrix.
  4. Use the reduce() function to iterate over the columns of the input matrix.
  5. In the reduce() function, use a lambda function to add the corresponding elements of each row of the input matrix.
  6. Use the zip() function to pair the elements of the rows.
  7. Append the result to a list.
  8. Print the resulting list of column sums.
     

Python3

# Python3 code to demonstrate
# Summation of each column in Matrix
 
from functools import reduce
 
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# Summation of each column in Matrix using functools.reduce()
res = reduce(lambda x,y: [i+j for i,j in zip(x,y)], test_list)
 
# print result
print("The Summation of each index list is : " + str(res))
 
# Time complexity: O(n*m)
# Auxiliary space: O(m), where n is the number of rows and m is the number of columns

                    

Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]

Time complexity: The time complexity of the reduce function is O(n) where n is the number of rows of the input matrix. Within each iteration of the reduce function, the time complexity of the lambda function is O(m) where m is the number of columns of the input matrix. Therefore, the overall time complexity of this approach is O(n*m).

Auxiliary space: The auxiliary space used by this approach is O(m), where m is the number of columns of the input matrix. This is because the resulting list of column sums has length equal to the number of columns of the input matrix. The lambda function also uses O(m) auxiliary space to store the result of the zip() function. Therefore, the overall auxiliary space of this approach is O(m).

Method 6: Using recursion

Step-by-step approach:

  • Define a recursive function that takes in a list of lists and an empty list to store the column-wise sums.
  • Base case: If the length of the first inner list is 0, return the list of column-wise sums.
  • Recursive case: Use a list comprehension to extract the first element of each inner list and append it to a new list. Recursively call the function with the remaining lists and the updated list of column-wise sums.
  • Use a for loop to iterate through the column-wise sums list and add the corresponding elements of each inner list.
  • Return the resulting list of sums.

Below is the implementation of the above approach:

Python3

def column_sums_recursive(lst, sums):
    if len(lst[0]) == 0:
        return sums
    else:
        first_elements = [sublst[0] for sublst in lst]
        sums.append(sum(first_elements))
        remaining_lists = [sublst[1:] for sublst in lst]
        return column_sums_recursive(remaining_lists, sums)
 
# initializing list
test_list = [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
 
# printing original list
print("The original list : " + str(test_list))
 
# Calculate column-wise sums using recursion
res_list = column_sums_recursive(test_list, [])
 
# print result
print("The Summation of each index list is : " + str(res_list))

                    

Output
The original list : [[3, 7, 6], [1, 3, 5], [9, 3, 2]]
The Summation of each index list is : [13, 13, 13]

Time complexity: O(nm), where n is the number of inner lists and m is the length of the longest inner list.
Auxiliary space: O(n), for the list of column-wise sums.



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