How do I sum the columns in 2D list?

Viewed 30995

Say I've a Python 2D list as below:

my_list =  [ [1,2,3,4],
             [2,4,5,6] ]

I can get the row totals with a list comprehension:

row_totals = [ sum(x) for x in my_list ]

Can I get the column totals without a double for loop? Ie, to get this list:

[3,6,8,10]
5 Answers

Use NumPy and transpose

import numpy as np
my_list = np.array([[1,2,3,4],[2,4,5,6]])
[ sum(x) for x in my_list.transpose() ]

Out[*]: [3, 6, 8, 10]

Or, simpler:

my_list.sum(axis = 0)
Related