How to perform element-wise addition of different length lists?
Assuming \"0\" for missing elements.
Note: len(a) will always be less than or equal to len(b)
exa
There's an alternative zip
that does not stop at the shortest: itertools.zip_longest(). You can specify a fill value for the shorter lists:
from itertools import zip_longest
result = [sum(n) for n in zip_longest(a, b, fillvalue=0)]
You can use izip_longest
:
>>> izip_longest(a,b,fillvalue=0)
<itertools.izip_longest object at 0x10bbd2520>
>>> list(_)
[(1, 1), (2, 2), (3, 3), (0, 4), (0, 5)]
Then you can do:
>>> [sum(t) for t in izip_longest(a,b,fillvalue=0)]
[2, 4, 6, 4, 5]
you can pad a with zeroes like this and use sum
a=[1,2,3]
b=[1,2,3,4,5]
a[:] = [a[i] if i < len(a) else 0 for i,j in enumerate(b)]
result=[sum(n) for n in zip(a,b)]
print result
results in
[2, 4, 6, 4, 5]