'In Python, how to numerically sum nested lists of integers: [[1,0], [1,1], [1,0]] → [3,1]

I have an array in the form of

a = [[1, 0], [1, 1], [0, 0], [0, 1], [1, 0]]

and I need to sum all values of the same index in the nested lists so that the above yields

[3,2]

This could get archieved by the following code

b = [0]*len(a[0])
for x in a:
  b = map(sum, zip(b,x))

Since a contains hundreds of lists, I wonder if there is a better way to do this. These nested lists have always the same length per run, in the example above 2, but it could well be just 1 or 3 or more, hence the initialization of b to [0]*len(a[0]).

Examples for the different lengths would be:

# nested lists always have 3 items
a = [[1, 0, 1], [1, 1, 1], [0, 0, 1], [0, 1, 1], [1, 0, 0]]
# result: [3, 2, 4]

# nested lists always have 1 item
a = [[1], [1], [0], [0], [1]]
# result: [3]

# mixed lengths would never happen
a = [[1], [0,1], [0], [0,1,1]] # no, this not!


Solution 1:[1]

I'd do it like this

b = list(map(sum,zip(*a)))
  1. *a expands a for passing in as individual parameters for a function
  2. zip(*a) gives us an iterator returning tuples of the first items in the sublists, the second items in the sublists, and so on
  3. map(sum,zip(*a)) adds up these tuples and returns a list or an iterator (depending on python version) of the sums
  4. The final list call turns this iterator into a list [python 3]

With

a = [[1, 0], [1, 1], [0, 0], [0, 1], [1, 0]]

the above call gives

[3,2]

Solution 2:[2]

You can simply transpose your initial matrix and sum each row:

b = [sum(e) for e in zip(*a)]

Solution 3:[3]

Solution

Use zip_longest (izip_longest in Python 2) with a fill value of 0 if your lists have different lengths:

>>> from itertools import zip_longest

>>> a = [[1, 0], [1, 1], [0, 0], [0, 1], [1, 0], [10, 20, 30]]
>>> [sum(x) for x in (zip_longest(*a, fillvalue=0))]
[13, 22, 30]

What you intended (guess)

b = [0] * max(map(len, a))
for x in a:
    res = list(map(sum, zip(b, x)))
    b[:len(res)] = res

Now for a:

a = [[1, 0], [1, 1], [0, 0], [0, 1], [1, 0], [10, 20, 30]]

you will get a b of:

[13, 22, 30]

Solution 4:[4]

This is exactly the kind of operation you want to harness numpy for.

import numpy as np
a = [[1, 0], [1, 1], [0, 0], [0, 1], [1, 0]]
arr = np.array(a)
arr.sum(axis=0)
=> array([3, 2])

If you must have the result as a list, as opposed to a numpy array, you can use the .tolist() method of numpy arrays.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew
Solution 2 Selcuk
Solution 3
Solution 4 shx2