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)) |
[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.
# 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)) |
[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)) |
[7, 18, 20]
Recommended Posts:
- Python | Check if a nested list is a subset of another nested list
- Count Negative Numbers in a Column-Wise and Row-Wise Sorted Matrix
- Python | Find maximum length sub-list in a nested list
- Python | Pair and combine nested list to tuple list
- Python | Convert a nested list into a flat list
- heapq in Python to print all elements in sorted order from row and column wise sorted matrix
- Python | Convert given list into nested list
- Python | Test for nested list
- Python | How to copy a nested list
- Python | Intersection of two nested list
- Nested List Comprehensions in Python
- Python | Split nested list into two lists
- Python | Remove duplicates from nested list
- Python | Remove all occurrences in nested list
- Python | Remove all duplicates and permutations in nested list
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.



