Sling Academy
Home/Python/Python: 3 Ways to Find the Product of a Numeric List

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

Last updated: June 18, 2023

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!

Next Article: Python: Count the Occurrences of Elements in a List (3 Ways)

Previous Article: Shuffling a List in Python (4 Approaches)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots