Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform element-wise multiplication of two lists?

People also ask

How do you multiply two elements in a list Python?

We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

Can we multiply 2 lists?

Multiply two lists using for loopWe can simply get the product of two lists using for loop. Through for loop, we can iterate through the list. Similarly, with every iteration, we can multiply the elements from both lists. For this purpose, we can use Zip Function.

Can we multiply 2 list in Python?

Multiply Two Lists in Python Using the numpy. multiply() Method. The multiply() method of the NumPy library in Python, takes two arrays/lists as input and returns an array/list after performing element-wise multiplication.


Use a list comprehension mixed with zip():.

[a*b for a,b in zip(lista,listb)]

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])

Use np.multiply(a,b):

import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)

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))]