+2 votes
in Programming Languages by (73.8k points)
edited by
How can I compute the product of all elements of a list in Python?

e.g.

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

answer=120

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

You can use prod() function of Numpy to compute the product of all elements of a list.

Here is an example:

>>> import numpy
>>> import numpy as np
>>> a=[1,2,3,4,5]
>>> np.prod(a)
120

Basic approach

>>> for v in a:
...   t=t*v
...
>>> t
120


...