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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

[7, 18, 20]

 

Method #2 : Using map() method

Another apporach is to use map(). We apply the sum function to each element in a column and find sum of each column accordingly.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

[7, 18, 20]

 
Method #3 : Using numpy.sum()

numpy.sum() function returns the sum of array elements over the specified axis.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

[7, 18, 20]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.