How to find multiply of all number in a list in python | Python Program

In this article, we will find the multiply of all numbers in a list using the python program.

We find the multiply of all the numbers in a list using 4 different methods:

  1. Using Traversal
  2. Using numpy.prod() 
  3. Using lambda function
  4. Using prod function


Using Traversal 

Explanation

  1. First, we iterate the list and initialize a variable total.
  2. Then, we update the value of total by = total * elements of list.
  3. Lastly, we prin the total.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# list
list = [1, 2, 3, 4]

# total
total = 1 

# iterate the elements of list
for ele in list:
    # multiple each elements with each other
    total *=ele

print("Multiply of all numbers in a list is:",total)

Output

Multiply of all numbers in a list is: 24


Using numpy.prod() 

Explanation

  1. First, we import the NumPy.
  2. Then we use numpy.prod() function that we the value of the multiplication of all number in a list.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# import numpy
import numpy

# list
list = [1, 2, 3, 4]

# use numpy.prod() to find the product of all the number
total = numpy.prod(list)

# prin the multipy of all the number
print("Multiply of all numbers in a list is:",total)

Output

Multiply of all numbers in a list is: 24


Using lambda function 

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# import reduce from the functools
from functools import reduce

# list
list = [1, 2, 3, 4]

# use lambda function to find muliply
total = reduce((lambda x, y: x * y), list)

# prin the multipy of all the number
print("Multiply of all numbers in a list is:",total)

Output

Multiply of all numbers in a list is: 24


Using Prod function 

Explanation

  1. First, we import the math module.
  2. Then, we find the products of all the numbers using math.prod() function.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# import math
import math

# list
list = [1, 2, 3, 4]

# use math.prod() function to find product 
total = math.prod(list)

# prin the multipy of all the number
print("Multiply of all numbers in a list is:",total)

Output

Multiply of all numbers in a list is: 24
Next Post Previous Post
No Comment
Add Comment
comment url