You can use the
ziplongest of the module
Just pass both lists and set the value fault to be used to fill in the missing values (in this case, I will use zero).
Since in their lists the elements are in quotation marks, they are actually strings, so I convert the elements to numbers using
from itertools import zip_longest list1 = ['1', '142', '33', '33', '9', '2'] list2 = ['1', '12', '7', '-2', '39', '11', '31', '49', '50', '1'] # scroll through the two lists, fill in the missing values with zero sums [int(e1) + int(e2) for e1, e2 in zip_longest(list1, list2, fillvalue=0)] print (sum) # [2, 154, 40, 31, 48, 13, 31, 49, 50, 1]
With this, we can browse both lists simultaneously, being at each iteration of the
for, the variable
e1 will be an element of
e2 will be an element of
list2. If the lists have different sizes, the missing values are completed by zero (the value defined by
The result is:
[2, 154, 40, 31, 48, 13, 31, 49, 50, 1]
Note that I used the syntax of understanding of the list to create the list of sums. The line that creates the sums is equivalent to:
sums  for e1, e2 in zip_longest (list1, list2, fillvalue = 0): sums.append (int (e1) + int (e2))
However, the understanding of the list is the most succinct and pythonic.