Aspen Grey
Aspen Grey

Reputation: 5

Python: Add Two Integer Lists of Different Lengths Together as One List

What I have:

first = [1,2,3]
second = [1,2,3,4]

What I want:

third = [2,4,6,4]

first + second = third

I've tryed using numpy and zips but they all stop after the smallest list is complete.

Upvotes: 0

Views: 28

Answers (1)

INGl0R1AM0R1
INGl0R1AM0R1

Reputation: 1628

from itertools import zip_longest


first = [1,2,3]
second = [1,2,3,4]
third = []

for i,z in zip_longest(first,second):
    if i  != None:
        third.append(i+z)
    else:
        a = 0 
        third.append(a+z)
print(third)

Here hope you like it

Upvotes: 0

Related Questions