Search code examples
pythonarraysnumpyaddition

Element wise addition of three list within an array


Suppose I have this array,

arr = [[7, 6], [4, 2, 7],[4,4,6,2]]

and I want to get a new list like this,

list = [15,12,13,2]

how can I get it? I am using the following method but it is not working:

list = np.sum(arr, axis=0)

Solution

  • You can use itertools.zip_longest:

    from itertools import zip_longest
    
    arr = [[7, 6], [4, 2, 7],[4,4,6,2]]
    
    out = list(map(sum, zip_longest(*arr, fillvalue=0)))
    

    Output: [15, 12, 13, 2]