Table of Contents
In this section of python programming, we will understand the different ways through which we can multiply the elements in the list and obtain the result. Python provides some in-built function which multiplies the elements in the list:
- prod() : we have to import numpy in our code.
- prod(): we have to import math in our code
- lambda() : we have to import reduce
from functools import reduce import numpy import math mul_res = 1 list = [1, 2, 3, 1, 5, 6, 2, 3, 1] # Using for loop for i in list: mul_res = mul_res * i print("Multiply using for loop: ",mul_res) #Using numpy.prod() result = numpy.prod(list) print("Multiply using numpy.prod(): ",result) # Using while math.prod() result1 = math.prod(list) print("Multiply using math.prod(): ",result1) #Using lambda() result2 = reduce((lambda n,m : n * m),list) print("Multiply using lambda(): ",result2)
In the above python code we used the different ways to multiply the elements in our list. The first method we used is simple traversal of elements and then multiplying the element. The second method is using numpy.prod(), it return integer or float values. Similarly math.prod() is used. The last method we used is the lambda, it contains the expression to be followed and returns the same. The reduce function takes the function lambda and list as argument and returns the output.