How to sum the values of each element of 2 lists with List Comprehension

Asked

Viewed 247 times

1

I have 2 lists and I want to add the element of each position on list a to the element of the same position on list b, only using <b>List Comprehension </b>

a = [1,2,3,4]
b = [5,6,7,8]

With map would look like this:

list(map(lambda x,y: x+y, a, b))

Out: [6, 8, 10, 12]

I would like to know how to do the corresponding using List Comprehension

1 answer

2


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)]

Browser other questions tagged

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