Sum of each element of two lists

Asked

Viewed 7,817 times

2

Is there any code that sums the elements of two lists, for example:

A=[1,2,3,4]

B=[2,4,5,6]

D=[3,6,8,10] # o elemento 3 e a soma dos elementos 1 e 2 da lista A e B

5 answers

5

The most direct solution is to use the native function zip which allows the joining/merging of two rolling stages.

zip(iteravel1, iteravel2)

The result is an object that when iterated functions as a list of tuples, in which each tuple has an element of each of the iterables. In the above example each tuple would have an element of the iteravel1 and another element of iteravel2.

In your code, assuming you have the list A and B created, just do so:

D = []
for elemA, elemB in zip(A, B):
    D.append(elemA + elemB) #adicionar em D a soma dos elementos de cada lista

Like the zip returns a list of tuples, the for is capturing each of the elements of the tuple in elemA and elemB

If you want to make code more compact and simple you can use list comprehensions:

D = [elemA + elemB for elemA, elemB in zip(A, B)]

The zip supports any amount of iterables to join/merge. In your example you could add 3 lists based on it zip:

A = [1, 2, 3, 4]
B = [2, 4, 5, 6]
C = [3, 6, 7, 8]

D = [elemA + elemB + elemC for elemA, elemB, elemC in zip(A, B, C)]
print(D) # [6, 12, 15, 18]

It is also important to say that you can solve without using zip but it wouldn’t be so intuitive and straightforward. A solution would be:

D = [B[posicao] + elemA for posicao, elemA in enumerate(A)]

In this last example I continued on the A obtaining either the element or the position by enumerate and then based on the position I went to get the corresponding element in B.

See all these examples in Ideone

  • Suggestion: being a little boring to the details, but the return of zip is not a list, but an object zip, which is iterable, so I would change "returns a list" to "returns an iterable object" xD

  • @Andersoncarloswoss I appreciate the comment as always. However I was literal to the documentation "This Function Returns a list of tuples, Where the i-th tuple contains the i-th element from each of the argument sequences or iterables". But confirming in the interpreter, the return is in fact a zip object. I will refract slightly, trying not to lose the original meaning. See if you think it’s good..

1

You can use Python’s own function, map().

She gets two values, one action and one target: map(ação, alvo) using a simple lambda you get the result in a simple line:

A = [1, 2, 3, 4]
B = [2, 4, 5, 6]

soma = list(map(lambda v1, v2: v1 + v2, A, B))

print(soma)

Note. 1: Notice that I converted the function result map on a list.

Note. 2: Notice that inside map has a lambda and "targets" which in this case are A and B, but could be a list with a set of numbers.

1

A = [ 1, 2, 3, 4 ]
B = [ 2, 4, 5, 6 ]

D = [ (a + b) for a, b in zip(A, B) ]

print(D)

0

This code only works if array A is the same size or smaller than array B:

 a=[1,2,3,4]
 b=[2,4,5,6]
 d=[]
 for x,y in enumerate(a): # Percorre o Array a enumerando suas posições
     d.append(y+b[x]) # somando elemento do array a com o elemento de mesma posição no array B
 print (d)

0

Another option would be this:

D = map(sum, zip(A, B))

basically a reduced form of the other answers.

  • It is worth mentioning that in this case, D not a list, but a generator.

Browser other questions tagged

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