Python Add Elements of a List (or Set, or whatever Data Type is appropriate)

859 Views Asked by At

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)

6

There are 6 best solutions below

4
On BEST ANSWER

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]
2
On

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
2
On

Three options:

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

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

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])
3
On
List ANSWER = ()
for index in range(0, len(A))
  ANSWER.append(A[index]+B[index])