Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum columns of an array in Python

How do I add up all of the values of a column in a python array? Ideally I want to do this without importing any additional libraries.

input_val = [[1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5]]

output_val = [3, 6, 9, 12, 15]

I know I this can be done in a nested for loop, wondering if there was a better way (like a list comprehension)?

like image 760
Alexander Avatar asked Apr 17 '17 21:04

Alexander


1 Answers

zip and sum can get that done:

Code:

[sum(x) for x in zip(*input_val)]

zip takes the contents of the input list and transposes them so that each element of the contained lists is produced at the same time. This allows the sum to see the first elements of each contained list, then next iteration will get the second element of each list, etc...

Test Code:

input_val = [[1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5]]

print([sum(x) for x in zip(*input_val)])

Results:

[3, 6, 9, 12, 15]
like image 66
Stephen Rauch Avatar answered Sep 22 '22 16:09

Stephen Rauch