Search code examples
pythonpandaslistzipelement

Adding or subtracting elements within list of list component wise


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?


Solution

  • 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]