0

Say I have a list of lists

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

And I want to transform this such that the individual indices are summed and I get:

[5, 7, 9]

Is there an easy combination of list comprehensions, zip(), sum() and so on for me to get this result without writing a clutter of for loops and accumulators?

Jared
  • 4,240
  • 4
  • 22
  • 27

2 Answers2

1

zip will take a splatted list/tuple, so you can use a comprehension to get a sum of any size:

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

s = [sum(a) for a in zip(*lol)]
print(s)

prints:

[12, 15, 18]
aghast
  • 14,785
  • 3
  • 24
  • 56
-1

You can use numpy, convert your list into an array and sum over 0 axis as follows:

import numpy as np
list_of_lists = [[1, 2, 3], [4, 5, 6]]
arr = np.array(list_of_lists)
result = np.sum(arr, axis=0)
print(result)

Although this would only work if all your lists within the list have the same length.

You can later convert the result into a list (if you need to) using:

result.tolist()
Ash
  • 3,428
  • 1
  • 34
  • 44