In this tutorial, we will discuss how to multiply all elements in a list in Python. There are multiple ways to perform multiplication within a list. We will discuss some of them here. If you want to see our other Step By Step Python List Tutorials Click here.
You can perform the multiplication of all elements or numbers of a list by a constant, scalar, or another list element. Some of the Methods to get the product of list in Python is given below:
- Traversal Method
- Numpy.prod()
- Lambda Function
- Math.Prod
Multiply all elements in a list using Traversal method
Using the traversal method to multiply all elements in List, we will run a for loop and traverse through the list. For loop will multiply every number to the previous number each time it iterates. For example, when the first time it iterates, it will multiply it with 1. The res is set to 1 and not 0 since every number multiplied by 0 is 0. The second time it iterates, it will multiply it with the product of 1 and the previous number and so on.
# Code Starts here
list = [1,2,3,4,5,6,7,8]
res = 1
for i in list:
res = res * i
print(res)
# code ends here
Output:
40320
Multiply each element in a list using numpy prod
Another method is using Numpy. To Multiply All Elements In List in Python, We will have to install NumPy first of all. Then we will use a built-in function of NumPy to get the product of the list.
# Using numpy.prod Method
import numpy
list = [1,2,3,4,5,6,7,8,9]
result = numpy.prod(list)
print(result)
#Code ends here
Output:
362880
multiply each number in a list using lambda function
Another approach to multiply all elements in the list in Python is using Lambda Function. Lambda’s definition does not include a “return” statement, it always contains an expression that is returned. Lambda Function can be used anywhere a function is expected. There is no need to assign it to a variable at all. This makes lambda functions simple to use. Similarly, reduce() function in Python takes in a function and a list as an argument. This performs a repetitive operation over the pairs of the list.
# Code starts here
from functools import reduce
list = [1, 2, 3, 4, 5, 6, 7]
res = reduce((lambda x, y: x * y), list))
print(res)
# Code ends here
Output:
5040
multiplication of all values in list using math.prod
The product of a list can also be calculated using a prod function included in Math Library. Let’s see it.
#Code starts here
from functools import reduce
list = [1, 2, 3, 4, 5, 6, 7]
res = reduce((lambda x, y: x * y), list))
print(res)
#Code ends here
See more Python tutorials