How to perform element-wise multiplication of two lists?
Solution 1:
Use a list comprehension mixed with zip()
:.
[a*b for a,b in zip(lista,listb)]
Solution 2:
Since you're already using numpy
, it makes sense to store your data in a numpy
array rather than a list. Once you do this, you get things like element-wise products for free:
In [1]: import numpy as np
In [2]: a = np.array([1,2,3,4])
In [3]: b = np.array([2,3,4,5])
In [4]: a * b
Out[4]: array([ 2, 6, 12, 20])
Solution 3:
Use np.multiply(a,b):
import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)
Solution 4:
You can try multiplying each element in a loop. The short hand for doing that is
ab = [a[i]*b[i] for i in range(len(a))]