# Python: 3 Ways to Find the Product of a Numeric List

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.

Syntax:

``math.prod(iterable, *, start=1)``

Where:

• `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.

Example:

``````import math

numbers = [2, 3, 4, 5, 6]
product = math.prod(numbers)
print(product) ``````

Output:

``720``

Performance: The `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:

1. Initialize a variable product with an initial value of 1.
2. Iterate through the list using a `for` loop.
3. Multiply each element with the product variable and update its value.
4. Return the final value of the product.

Code example:

``````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)``````

Output:

``5040``

Performance: This approach works with all versions of Python. It has a time complexity of `O(n)`, where `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.

Code example:

``````from functools import reduce

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

product = reduce(lambda x, y: x * y, numbers)
print(product)``````

Output:

``40320``

Performance: The time complexity here is `O(n)`, similar to the preceding approaches.

## Conclusion

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!

Subscribe
Notify of 