Is there any way to sum over multiple lists, index by index, to get one final list? Knowing that these lists might not have the same length? For example, with these
[2,4,0,0], [0,0,2], [0,4]
I would like to have
[2,8,2,0]
as a result.
I haven't found any result so far.
You can use itertools.zip_longest
with the fillvalue
argument set to 0
. If you use this in a list comprehension, you can unpack and zip the inner lists and add them in an element-wise fashion.
>>> from itertools import zip_longest
>>> [sum(i) for i in zip_longest(*l, fillvalue=0)]
[2, 8, 2, 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With