GoCoding.org

Program to multiply all the elements in the list using Python

by | Jan 30, 2021 | Python Programs

Introduction

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

 

Program to multiply all the elements in the list using Python

Program

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)

 

Output

Program to multiply all the elements in the list using Python Output

Explanation

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.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.