How to compute the multiplication of a list in python?
a = [1,2,3,4,5]
for loop
The most intuitive and easy solution.
res = 1
for i in a:
res *= i
math.prod or np.prod
math
or numpy
module has an embedded function for multiplication of list.
import math
res = math.prod(a)
or
import numpy as np
res = np.prod(a)
functools.reduce
This is personally my favourite, it is an elegant one-liner with easy extensions to compute other tasks related to "reduce a list to a single number".
import functools
res = functools.reduce(lambda x, y: x * y, a)
say if you want to piece together a list of strings
functools.reduce(lambda x,y: x+y, ["hi,", " world"])
say if you want to add a list of nums:
functools.reduce(lambda x,y: x+y, [1, 2, 3, 4])
Top comments (0)