Find the sum of two lists of lists element-wise [closed]

You could just use zip like,

>>> list1
[[1, 2, 3], [4, 5, 6]]
>>> list2
[[10, 2, 3], [11, 5, 6]]
>>> [[x+y for x,y in zip(l1, l2)] for l1,l2 in zip(list1,list2)]
[[11, 4, 6], [15, 10, 12]]

or if you are not sure, if both list will be of same length, then you can use zip_longest (izip_longest in python2) from itertools and use the fillvalue like,

>>> import itertools
>>> y = itertools.zip_longest([1,2], [3,4,5], fillvalue=0)
>>> list(y)
[(1, 3), (2, 4), (0, 5)]

that then you can use it for unequal sized data like,

>>> from itertools import zip_longest
>>> list1=[[1, 2, 3], [4, 5]]
>>> list2=[[10, 2, 3], [11, 5, 6], [1,2,3]]
>>> [[x+y for x,y in zip_longest(l1, l2, fillvalue=0)] for l1,l2 in zip_longest(list1,list2, fillvalue=[])]
[[11, 4, 6], [15, 10, 6], [1, 2, 3]]

Leave a Comment