Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Column-wise sum of nested list

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading