How to add the integers in one list to another in Python

Viewed 40

I have two lists using python, let's say:

lst = [1, 1, 2]
lst2 = [1, 1]

And I'm trying to "add" the elemtents of lst with lst2 such that I get: [2, 2, 2]

I have tried doing:

lst + lst2

This only get's me [1, 1, 2, 1, 1,]

Any help would be much appreciated!

3 Answers

Maybe this?

>>> import itertools
>>> [sum(pair) for pair in itertools.zip_longest(lst, lst2, fillvalue=0)]
[2, 2, 2]

You can use itertools.zip_longest with fillvalue=0:

from itertools import zip_longest

lst = [a + b for a, b in zip_longest(lst, lst2, fillvalue=0)]
print(lst)

Prints:

[2, 2, 2]

if you prefer to do it without iterator:

lst3 = [lst[i]+lst2[i] for i in range(min(len(lst), len(lst2)))]+lst[min(len(lst), len(lst2)):]+lst2[min(len(lst), len(lst2)):]
Related