Python | Column wise sum of nested list
Last Updated :
17 Apr, 2023
Given a nested list (where sublists are of equal length), write a Python program to find the column-wise sum of the given list and return it in a new list.
Examples:
Input : [[1, 5, 3],
[2, 7, 8],
[4, 6, 9]]
Output : [7, 18, 20]
Input : [[20, 5],
[2, 54],
[45, 9],
[72, 3]]
Output : [139, 71]
Method #1:
Python3
def column_sum(lst):
res = []
for i in range ( 0 , len (lst)):
s = 0
for j in range ( 0 , len (lst[i])):
s + = lst[j][i]
res.append(s)
return res
lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]]
print (column_sum(lst))
|
Time Complexity: O(n^2), where n is the length of the longest sublist in the nested list.
Auxiliary Space: O(n), where n is the number of columns in the nested list.
Method #2: zip using list comprehension We can find sum of each column of the given nested list using zip function of python enclosing it within list comprehension.
Python3
def column_sum(lst):
return [ sum (i) for i in zip ( * lst)]
lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]]
print (column_sum(lst))
|
Time Complexity: O(n) where n is the number of elements in the list
Auxiliary Space: O(n), where n is the length of the list
Method #3: Using map() method Another approach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.
Python3
def column_sum(lst):
return list ( map ( sum , zip ( * lst)))
lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]]
print (column_sum(lst))
|
Time Complexity: O(n), where n is the number of elements in the list
Auxiliary Space: O(n), where n is the number of elements in the list
Method #4: Using numpy.sum() numpy.sum() function returns the sum of array elements over the specified axis.
Python3
from numpy import array
def column_sum(lst):
arr = array(lst)
return sum (arr, 0 ).tolist()
lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]]
print (column_sum(lst))
|
Method #5: Using dictionary
Here is another approach using a dictionary to store the sums of each column. This method iterates through each element in the nested list and adds it to the corresponding key in the dictionary.
Python3
def column_sum(lst):
column_sums = {i: 0 for i in range ( len (lst[ 0 ]))}
for sublist in lst:
for i, val in enumerate (sublist):
column_sums[i] + = val
return list (column_sums.values())
lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]]
print (column_sum(lst))
|
Time complexity: O(nm), where n is the number of sublists and m is the number of elements in each sublist.
Auxiliary Space: O(m), as we store a sum for each column in the dictionary.
Please Login to comment...