Sling Academy
Home/Python/Python: Return Multiple Results from a Function (3 Ways)

Python: Return Multiple Results from a Function (3 Ways)

Last updated: July 10, 2023

This concise, example-based article will walk you through 3 common approaches for returning multiple results from a function in Python. Without any further ado, let’s get started.

Using a Tuple

You can return multiple values as a tuple, which allows you to group multiple values into a single object. This technique is simple, straightforward, widely used, and suitable for returning a small number of results. It requires unpacking the tuple when calling the function.

Example:

def get_stats(numbers):
    min_val = min(numbers)
    max_val = max(numbers)
    avg_val = sum(numbers) / len(numbers)
    return min_val, max_val, avg_val

min_val, max_val, avg_val = get_stats([1, 2, 3, 4, 5])
print(f"Min: {min_val}, Max: {max_val}, Avg: {avg_val}")

Output:

Min: 1, Max: 5, Avg: 3.0

Using a List

In this method, we’ll return multiple values as a list, which allows for flexibility in adding or removing elements. It’s easy to manipulate the result list, suitable for returning a variable number of results.

Example:

def get_stats(numbers):
    min_val = min(numbers)
    max_val = max(numbers)
    avg_val = sum(numbers) / len(numbers)
    
    return [min_val, max_val, avg_val]

[min_val, max_val, avg_val] = get_stats([1, 2, 3, 4, 5])
print(f"Min: {min_val}, Max: {max_val}, Average: {avg_val}")

Another way to work with the returned values is to use indices like this:

def get_stats(numbers):
    min_val = min(numbers)
    max_val = max(numbers)
    avg_val = sum(numbers) / len(numbers)
    return [min_val, max_val, avg_val]

result = get_stats([1, 2, 3, 4, 5])
min_val = result[0]
max_val = result[1]
avg_val = result[2]

print(f"Min: {min_val}, Max: {max_val}, Average: {avg_val}")

Using a Dictionary

An alternative solution is to return multiple values as a dictionary. This way provides a named interface to access specific results, suitable for returning a set of related values. However, the code will be a little bit longer since it requires accessing elements by key when using the function’s result.

Example:

def get_stats(numbers):
    stats = {
        'min': min(numbers),
        'max': max(numbers),
        'avg': sum(numbers) / len(numbers)
    }
    return stats

result = get_stats([1, 2, 3, 4, 5])

min_val = result['min']
max_val = result['max']
avg_val = result['avg']

print(f"Min: {min_val}, Max: {max_val}, Avg: {avg_val}")

Next Article: Python Function: Keyword & Positional Arguments

Previous Article: Python match/case statement (with examples)

Series: Control Flow & Functions in Python

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