You can use the method zip_longest
module itertools
.
Just pass the two lists and set the value default to be used to fill in the missing values (in this case I will use zero).
As in your lists the elements are in quotes, they are actually strings, so I convert the elements to numbers using int()
:
from itertools import zip_longest
list1 = ['1', '142', '33', '33', '9', '2']
list2 = ['1', '12', '7', '-2', '39', '11', '31', '49', '50', '1']
# percorrer as duas listas, preencher os valores faltantes com zero
somas = [int(e1) + int(e2) for e1, e2 in zip_longest(list1, list2, fillvalue=0)]
print(somas) # [2, 154, 40, 31, 48, 13, 31, 49, 50, 1]
With this we can go through the two lists simultaneously, with each iteration of the for
, the variable e1
will be an element of lista1
, and e2
will be an element of lista2
. If the lists have different sizes, the missing values are filled with zero (the value defined by fillvalue
).
The result is:
[2, 154, 40, 31, 48, 13, 31, 49, 50, 1]
Note that I used the syntax of comprehensilist on to create the list of sums. The line that creates the sums is equivalent to:
somas = []
for e1, e2 in zip_longest(list1, list2, fillvalue=0):
somas.append(int(e1) + int(e2))
But the comprehensilist on is the most succinct and pythonic.
muuuuuito thanks! now everything makes more sense I understood the shape more easily without using the list comprehension
– Bruna