Home » Python » Element-wise addition of 2 lists?

Questions:

I have now:

list1=[1, 2, 3]
list2=[4, 5, 6]

I wish to have:

[1, 2, 3]
+  +  +
[4, 5, 6]
||
[5, 7, 9]

Simply an element-wise addition of two lists.

I can surely iterate the two lists, but I don’t want do that.

What is the most Pythonic way of doing so?

[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
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

Questions:

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 np
In : 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 + vector2
In : print sum_vector
[5 7 9]

just like in Matlab.

Timing to compare with Ashwini’s fastest version:

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

In : timeit vector1 + vector2
1000 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.

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

Questions:

As described by others, a fast and also space efficient solution is using numpy (np) with it’s built-in vector manipulation capability:

1. With Numpy

x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y

2. With built-ins

2.1 Lambda

list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)

Notice that map() supports multiple arguments.

2.2 zip and list comprehension

list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]

Questions:

Perhaps “the most pythonic way” should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.

Example:

import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]

>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)

Which result might you want if this were in a function in your problem?

Questions:

Use map with lambda function:

>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]

Questions:

This will work for 2 or more lists; iterating through the list of lists, but using numpy addition to deal with elements of each list

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

lists = [list1, list2]
list_sum = np.zeros(len(list1))
for i in lists:
list_sum += i
list_sum = list_sum.tolist()

[5.0, 7.0, 9.0]

Questions:

I haven’t timed it but I suspect this would be pretty quick:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

[5, 7, 9]

Questions:

If you need to handle lists of different sizes, worry not! The wonderful itertools module has you covered:

>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>

In Python 2, zip_longest is called izip_longest.

Questions:
[list1[i] + list2[i] for i in range(len(list1))]

Questions:

Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!

To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.

So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.

# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]

The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).

Questions: 