Adding or subtracting elements within list of list component wise

Viewed 62

How do I add elements of lists within a list component wise?

p=[[1,2,3],[1,0,-1]]

I have tried the following:

list(map(sum,zip(p[0],p[1])))

Will get me [2,2,2] which is what I need. But how to extend it for a variable number of lists? For example, p=[[1,2,3],[1,0,-1],[1,1,1]] should yield [3,3,3].

A solution I figured out is the following:

import pandas as pd
p=[[1,2,3],[1,0,-1],[1,1,1]]
list(pd.DataFrame(p).sum())

Is there a more "Pythonic" way to solve this problem?

2 Answers

Use * for unpack lists:

a = list(map(sum,zip(*p)))
print (a)
[3, 3, 3]

In numpy solution is similar like in pandas:

a = np.array(p).sum(axis=0).tolist()
print(a)
[3, 3, 3]

You can use * to unpack the list and sum to sum it up. If you are uncomfortable with the map function you can do it like this:

p = [[1, 2, 3], [4, 5, 6], [-5,-7,-9]]

sum_list = [sum(elem) for elem in zip(*p)]

print(sum_list)
Related