Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum lists of variable lengths element-wise

Tags:

python

If I have a list of lists, and each nested list contains numbers, how can I add all of these lists element-wise into a single array?

i.e.

listOne = [1, 2, 3]
listTwo = [4, 5, 6]
listThree = [7, 8, 9, 10]
allLists = [listOne, listTwo, listThree]

total = add(allLists)
print total

output should be [12, 15, 18, 10]

like image 715
Apollo Avatar asked Jan 29 '26 22:01

Apollo


1 Answers

Use izip_longest to remap rows/columns (like zip but to the longest element rather than shortest), filling shorter items 0

from itertools import izip_longest
total = [sum(x) for x in izip_longest(*allLists, fillvalue=0)]

Outputs:

[12, 15, 18, 10]

Also for your edification, the intermediate output of the zip_longest is:

[(1, 4, 7), (2, 5, 8), (3, 6, 9), (0, 0, 10)]
like image 125
mhlester Avatar answered Feb 01 '26 20:02

mhlester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!