Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiply list of lists element-wise

Tags:

python

list

numpy

What is the neatest way to multiply element-wise a list of lists of numbers?

E.g.

[[1,2,3],[2,3,4],[3,4,5]]

-> [6,24,60]
like image 487
user973758 Avatar asked Feb 03 '14 23:02

user973758


People also ask

Can you multiply a list by a list in Python?

Multiply two lists using for loop We 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.

How can I multiply all items in a list together with 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 in Python?

Multiply Two Python Lists Element-wise Using Numpy, that allows us to multiply two arrays. In order to accomplish this, it would seem that we first need to convert the list to a numpy array. However, numpy handles this implicitly. The method returns a numpy array.

Does NumPy do element-wise multiplication?

multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.


2 Answers

Use np.prod:

>>> a = np.array([[1,2,3],[2,3,4],[3,4,5]])
>>> np.prod(a,axis=1)
array([ 6, 24, 60])
like image 112
Daniel Avatar answered Sep 28 '22 07:09

Daniel


Use a list comprehension and reduce:

>>> from operator import mul
>>> lis = [[1,2,3],[2,3,4],[3,4,5]]
>>> [reduce(mul, x) for x in lis]
[6, 24, 60]
like image 23
Ashwini Chaudhary Avatar answered Sep 28 '22 06:09

Ashwini Chaudhary