sum multiple list elements at the same time(python)

Question:

How can I sum multiple list elements at the same time?
For example, something like this in Python:

Our lists (input):

[3, 3, 1, 1, 1, 1, 1]
[1, 1, 4, 5, 6, 7, 8]

Output:

[4, 4, 5, 6, 7, 8, 9]

Note: we don’t know how many list will be given to us.

Asked By: sperite

||

Answers:

This should do the job

l1 = [3, 3, 1, 1, 1, 1, 1]
l2 = [1, 1, 4, 5, 6, 7, 8]

l3 = [sum(t) for t in zip(l1, l2)]
    
print(l3)
Answered By: Ferre Meuleman

This can be done very easily and efficiently using pandas.

lists = [[3, 3, 1, 1, 1, 1, 1], [1, 1, 4, 5, 6, 7, 8]]
df = pd.DataFrame(data=lists)
out = df.sum().tolist()

print(out):

[4, 4, 5, 6, 7, 8, 9]

It should work with any number of lists.

Answered By: SomeDude

If you have varying number of list as input , you can try the below.,

note : input the numbers in list as comma-seperated values


Console

1,2,3

2,3,1

[3, 5, 4]


import pandas as pd

ls = []
while True:
    inp = input()
    if inp == "":
        break
    ls.append(list(map(int,inp.split(","))))

df = pd.DataFrame(data=ls)
out = df.astype(int).sum().tolist()
print(out)
Answered By: Mohamed Shabeer kp

As we don’t know how many lists there will be, and I assume their lengths could be different, using the zip_longest function from itertools is the perfect tool:

from itertools import zip_longest
    
l1 = [3, 3, 1, 1, 1, 1, 1]
l2 = [1, 1, 4, 5, 6, 7, 8]
l3 = [1, 1, 4, 5, 6, 7, 8, -1]
l4 = [-105]

lists = [l1,l2,l3,l4]

summed = list(map(sum,zip_longest(*lists,fillvalue=0)))
print(summed)

Output:

[-100, 5, 9, 11, 13, 15, 17, -1]
Answered By: Gábor Fekete
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.