Python | Column wise sum of nested list
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 : 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 program to Column wise sum of nested list def column_sum(lst): return [ sum (i) for i in zip ( * lst)] # Driver code lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]] print (column_sum(lst)) |
Output:
[7, 18, 20]
Method #2 : 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 program to Column wise sum of nested list def column_sum(lst): return list ( map ( sum , zip ( * lst))) # Driver code lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]] print (column_sum(lst)) |
Output:
[7, 18, 20]
Method #3 : Using numpy.sum()
numpy.sum() function returns the sum of array elements over the specified axis.
# Python3 program to Column wise sum of nested list from numpy import array def column_sum(lst): arr = array(lst) return sum (arr, 0 ).tolist() # Driver code lst = [[ 1 , 5 , 3 ], [ 2 , 7 , 8 ], [ 4 , 6 , 9 ]] print (column_sum(lst)) |
Output:
[7, 18, 20]