I have now:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
I wish to have:
[1, 2, 3]
+ + +
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)]
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]
list_sum = (np.add(list1, list2)).tolist()
[5, 7, 9]
a_list = []
b_list = []
for i in range(1,100):
a_list.append(random.randint(1,100))
for i in range(1,100):
a_list.append(random.randint(101,200))
[sum(x) for x in zip(a_list , b_list )]
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 [1]: import numpy as np
In [2]: vector1 = np.array([1, 2, 3])
In [3]: vector2 = np.array([4, 5, 6])
Doing the element-wise addition is now as trivial as
In [4]: sum_vector = vector1 + vector2
In [5]: print sum_vector
[5 7 9]
just like in Matlab.
Timing to compare with Ashwini's fastest version:
In [16]: from operator import add
In [17]: n = 10**5
In [18]: vector2 = np.tile([4,5,6], n)
In [19]: vector1 = np.tile([1,2,3], n)
In [20]: list1 = [1,2,3]*n
In [21]: list2 = [4,5,6]*n
In [22]: timeit map(add, list1, list2)
10 loops, best of 3: 26.9 ms per loop
In [23]: 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
.
[a + b for a, b in zip(list1, list2)]
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)]
[2]
>>> 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?