I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab.
This is how I would do it in Matlab.
a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]
A list comprehension would give 16 list entries, for every combination x * y
of x
from a
and y
from b
. Unsure of how to map this.
If anyone is interested why, I have a dataset, and want to multiply it by Numpy.linspace(1.0, 0.5, num=len(dataset)) =)
.
Since you're already using
numpy
, it makes sense to store your data in anumpy
array rather than a list. Once you do this, you get things like element-wise products for free:you can use this for lists of the same length
Use np.multiply(a,b):
gahooa's answer is correct for the question as phrased in the heading, but if the lists are already numpy format or larger than ten it will be MUCH faster (3 orders of magnitude) as well as more readable, to do simple numpy multiplication as suggested by NPE. I get these timings:
i.e. from the following test program.
To maintain the list type, and do it in one line (after importing numpy as np, of course):
or
Fairly intuitive way of doing this: