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.
Some of the Methods to get the product of list in Python are given below:
- Traversal Method
- Lambda Function
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. You can also try it yourself by changing the code.
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 builtin 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)
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 simply 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.
from functools import reduce list = [1, 2, 3, 4, 5, 6, 7] res = reduce((lambda x, y: x * y), list)) print(res)
The product of a list can also be calculated using a prod function included in Math Library. Let’s see it.
import math list1 = [1, 2, 3, 4, 5, 6, 7, 8] res = math.prod(list) print(res)
See more Python tutorials