This pithy, example-based article will walk you through several distinct ways to find the product of a numeric list (a list that contains only numbers) in Python. We’ll also discuss the performance of each approach so you can understand how fast it is.
Using the math.prod() function
This function is only available in Python 3.8 and newer versions of the programming language. It is used to calculate the product of a sequence of numbers.
math.prod(iterable, *, start=1)
iterable(required): An iterable sequence (e.g., list, tuple, set) of numbers for which the product is calculated. If it contains non-numeric elements, you’ll get an unexpected output.
start(optional): It specifies the initial value of the product. The default value is 1.
import math numbers = [2, 3, 4, 5, 6] product = math.prod(numbers) print(product)
math.prod() function provides an optimized implementation for computing the product of a sequence. It’s fast and reliable. However, it requires Python 3.8 at least (which was release in October, 2019).
Using a for loop
You can manually find the product of a numeric list by using a
for loop. The process is as follows:
- Initialize a variable product with an initial value of 1.
- Iterate through the list using a
- Multiply each element with the product variable and update its value.
- Return the final value of the product.
def product_with_for_loop(lst): product = 1 for num in lst: product *= num return product nums = [2, 3, 4, 5, 6, 7] result = product_with_for_loop(nums) print(result)
Performance: This approach works with all versions of Python. It has a time complexity of
n is the length of the list. It iterates through each element in the list once.
Using the reduce() function
This approach applies the multiplication operation to all elements of the input list using the
reduce() function from the
functools module. The syntax is neat and elegant.
from functools import reduce numbers = [1, 2, 3, 4, 5, 6, 7, 8] product = reduce(lambda x, y: x * y, numbers) print(product)
Performance: The time complexity here is
O(n), similar to the preceding approaches.
We’ve seen some different ways to get the product of a numeric list in Python. Their performance are quite similar. Choose from the the one that matches your coding style to go with. If you have any questions, please comment. Happy coding & have a nice day!