Column-wise sum of nested list [duplicate]

Is there a more pythonic or more simple way to accomplish this?

I am taking the column-wise sum of items in a nested list. I have a working example but I’m sure nested loops are not the way to do. There has to be something, maybe in NumPy or something, that already does this?

So it’s the sum of the first elements in each nested list, the sum of the second elements in each nested list, etc…

list_a = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

def sum_columns(nested_list):
    
    col_sums = []
    col_len = len(list_a[0])
    
    for col in range(col_len):
        
        col_sum = 0
        
        for row in list_a:
            col_sum += row[col]
            
        col_sums.append(col_sum)
        
    return col_sums
        
sum_columns(list_a)

>> [12, 15, 18]

I also tried list comprehensions because I think that would be faster but the logic of it seems too complicated because of the nested loops and I was not able to get that to work.

You can use a zip and this unpacking trick:

[sum(i) for i in zip(*list_a)]

There is always an argument that this is a bit cryptic, but it does the job:

[12, 15, 18]

Leave a Comment