Question

Is there an easy way to add the members of two equally sized lists (or tuple or whatever data type would work best)?

I have, for example a and b with 2 elements:

a = (0, 10)
b = (0, -10)

I want to add them and get as result:

result = (0, 0)

NOT (0, 10, 0, -10)

Was it helpful?

Solution

You can do this in one line in Python:

map(sum, zip(A, B))

Example:

>>> B = [1, 2, 3, 4]
>>> C = [1, 2, 4, 8]
>>> map(sum, zip(B, C))
[2, 4, 7, 12]

OTHER TIPS

Three options:

>>> [a+b for (a,b) in zip(A,B)]
>>> map(int.__add__, A, B)
>>> map(sum, zip(A,B))

if you want to operate with list of numbers use numpy

>>> a = [1,2]
>>> b = [1,2]
>>> import numpy as np
>>> np.add(a,b)
array([2, 4])
>>> 

You can use numpy to add the lists:

add(array([-1.2, 1.2]), array([1,3]))

and the result it:

array([-0.2, 4.2])
List ANSWER = ()
for index in range(0, len(A))
  ANSWER.append(A[index]+B[index])

yes, just do this

map(sum,zip(A,B)

or, (actually clearly faster)

u=map(lambda a,b:a+b,A,B)

Timing examples:

A=range(3000)
B=range(3000)
for i in range(15000):
 u=map(lambda a,b:a+b,A,B)   # takes about 7.2 seconds
 # u=map(sum,zip(A,B))       # takes about 11 seconds
 # u=map(int.__add__,A,B) # (Edward Loper) actually also consistently ~0.5 sec slower than lambda
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top