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:
- Using Traversal
- Using numpy.prod()
- Using lambda function
- Using prod function
Using Traversal
Explanation
- First, we iterate the list and initialize a variable total.
- Then, we update the value of total by = total * elements of list.
- 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
- First, we import the NumPy.
- 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
- First, we import the math module.
- 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