Sum of each element of two lists

2

There is some code that adds 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
    
asked by anonymous 23.06.2018 / 00:27

4 answers

5

The most straightforward solution is to use the zip native function that allows merge / merge two iterable.

zip(iteravel1, iteravel2)

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

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

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

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

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

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

The zip supports any number of iterables to join / merge. In your example you could do the sum of 3 lists based on the same 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's also important to say that you can resolve without using zip but it would not look so intuitive and straightforward. One solution would be:

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

In this last example, I'll try about A getting both element and position through enumerate and then based on position I fetched the corresponding element in B .

See all these examples on Ideone

    
23.06.2018 / 11:35
1
A = [ 1, 2, 3, 4 ]
B = [ 2, 4, 5, 6 ]

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

print(D)
    
23.06.2018 / 00:33
0

This code works only 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)
    
25.06.2018 / 14:14
0

Another option would be this here:

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

basically a reduced form of the other answers.

    
25.06.2018 / 17:09