You can create a Comprehension List by getting the size of one of the lists to insert into one for..range
and then return the sum of the position element i
of the lists a
and b
. See the code below:
a = [1,2,3,4]
b = [5,6,7,8]
r = [a[i] + b[i] for i in range(len(a))]
Of course for this to work, both lists need to have the same amount of elements or else will be generated a IndexError
. To get around this problem, we can look at the maximum size that we can go through, in this way:
a = [1,2,3,4]
b = [5,6,7,8]
limit = len(min(a, b)) # Obtém o tamanho da menor lista
r = [a[i] + b[i] for i in range(limit)]
If you don’t want to take the trouble of checking, you can use a zip()
to join each element of the lists and then use the function sum()
to add the returned elements. Example:
a = [1,2,3,4]
b = [5,6,7,8]
r = [sum(values) for values in zip(a, b)]