Add list values with different sizes

Asked

Viewed 591 times

6

I have two lists with varying numbers and sizes. For example:

array 1
['1', '142', '33', '33', '9', '2']

array 2
['1', '12', '7', '-2', '39', '11',  '31', '49', '50', '1']

How do I make a loop to add the first item of array 1 to the first item of array 2 and so on? If any of them do not have the required amount of items, it should add up to zero, thus: 1+1, 142+12, 33+7, ..., 2+11, 0+31, 0+49, ...

1 answer

12


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.

  • 1

    muuuuuito thanks! now everything makes more sense I understood the shape more easily without using the list comprehension

Browser other questions tagged

You are not signed in. Login or sign up in order to post.