How to sum the columns of a nested list in Python

3 Answers

0 votes
nested_list = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]]

num_columns = len(nested_list[0])
column_sum = [0] * num_columns

for row in nested_list:
   for i in range(num_columns):
      column_sum[i] += row[i]

print("The column sum:",column_sum)

 
 
'''
run:
 
The column sum: [12, 15, 18]
 
'''

 



answered Jan 10 by avibootz
0 votes
nested_list = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]]

column_sum = [sum(column) for column in zip(*nested_list)]

print("The column sum:",column_sum)

 
 
'''
run:
 
The column sum: [12, 15, 18]
 
'''

 



answered Jan 10 by avibootz
0 votes
import numpy as np

nested_list = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]]
               
arr = np.array(nested_list)
column_sum = np.sum(arr, axis=0)

print("The column sum:",column_sum)

 
 
'''
run:
 
The column sum: [12, 15, 18]
 
'''

 



answered Jan 10 by avibootz
...