Element-wise addition of 2 lists? Element-wise addition of 2 lists? python python

# Element-wise addition of 2 lists?

``>>> from operator import add>>> list( map(add, list1, list2) )[5, 7, 9]``

or `zip` with a list comprehension:

``>>> [sum(x) for x in zip(list1, list2)][5, 7, 9]``

### Timing comparisons:

``>>> list2 = [4, 5, 6]*10**5>>> list1 = [1, 2, 3]*10**5>>> %timeit from operator import add;map(add, list1, list2)10 loops, best of 3: 44.6 ms per loop>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]10 loops, best of 3: 71 ms per loop>>> %timeit [a + b for a, b in zip(list1, list2)]10 loops, best of 3: 112 ms per loop>>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]1 loops, best of 3: 139 ms per loop>>> %timeit [sum(x) for x in zip(list1, list2)]1 loops, best of 3: 177 ms per loop``

The others gave examples how to do this in pure python. If you want to do this with arrays with 100.000 elements, you should use numpy:

``In : import numpy as npIn : vector1 = np.array([1, 2, 3])In : vector2 = np.array([4, 5, 6])``

Doing the element-wise addition is now as trivial as

``In : sum_vector = vector1 + vector2In : print sum_vector[5 7 9]``

just like in Matlab.

Timing to compare with Ashwini's fastest version:

``In : from operator import addIn : n = 10**5In : vector2 = np.tile([4,5,6], n)In : vector1 = np.tile([1,2,3], n)In : list1 = [1,2,3]*nIn : list2 = [4,5,6]*nIn : timeit map(add, list1, list2)10 loops, best of 3: 26.9 ms per loopIn : timeit vector1 + vector21000 loops, best of 3: 1.06 ms per loop``

So this is a factor 25 faster! But use what suits your situation. For a simple program, you probably don't want to install numpy, so use standard python (and I find Henry's version the most Pythonic one). If you are into serious number crunching, let `numpy` do the heavy lifting. For the speed freaks: it seems that the numpy solution is faster starting around `n = 8`.

``[a + b for a, b in zip(list1, list2)]`` 