How to Return Multiple Values from a Function in Python?

Have you ever needed to return more than one value from a function in Python? This is a common requirement for Python developers, and Python makes it incredibly easy. In this tutorial, I will explain how to return multiple values from a function in Python with examples.

To return multiple values from a function in Python, simply separate them with commas in the return statement. This creates a tuple, which you can then unpack or use directly. For example, def get_coordinates(): return 10, 20 will return (10, 20), allowing you to handle multiple pieces of data efficiently.

Return Multiple Values from a Function in Python

There will be many scenarios where you need to return multiple values from a Python function. There are various ways to do this, from the basic to the advanced.

Basic Syntax

In Python, you can return multiple values from a function by simply separating them with commas in the return statement. These values are returned as a tuple. Here’s a basic example that returns two values from the Python function.

def get_coordinates():
    x = 10
    y = 20
    return x, y

coordinates = get_coordinates()
print(coordinates)  # Output: (10, 20)

In this example, the get_coordinates function returns two values, x and y, which are then captured as a tuple. Here is the output in the screenshot below:

python function return two values

Check out How to Call a Function in Python?

Using Tuples

Tuples are another way to return multiple values from a Python function. When you separate values with commas in the return statement, Python automatically packs them into a tuple.

def calculate_area_and_perimeter(length, width):
    area = length * width
    perimeter = 2 * (length + width)
    return area, perimeter

result = calculate_area_and_perimeter(5, 3)
print(result)  # Output: (15, 16)

In this example, the function calculate_area_and_perimeter returns both the area and the perimeter of a rectangle.

Here is the output in the screenshot below:

python function return multiple values tuple

Using Lists

If you prefer, you can also return multiple values as a list. This can be useful if you need a mutable collection of values. Here is another example of returning multiple values as a list from a function in Python.

def get_even_numbers(n):
    evens = [i for i in range(n) if i % 2 == 0]
    total = len(evens)
    return [evens, total]

result = get_even_numbers(10)
print(result)  # Output: [[0, 2, 4, 6, 8], 5]

Here, the function get_even_numbers returns a list of even numbers up to n and the total count of those numbers.

Here is the output in the screenshot below:

python function return multiple values

Check out Python Function Examples with Parameters

Using Dictionaries

Dictionaries are another excellent way to return multiple values from a Python function, especially when you want to label each value for clarity.

Here is an example and the complete code.

def get_user_info():
    user = {
        "name": "John Doe",
        "age": 30,
        "email": "john.doe@example.com"
    }
    return user

user_info = get_user_info()
print(user_info)  # Output: {'name': 'John Doe', 'age': 30, 'email': 'john.doe@example.com'}

In this example, the function get_user_info returns a dictionary containing user information.

You can see the exact output in the screenshot below.

python function return multiple values example

Using Named Tuples

Named tuples offer a way to return multiple values with more readability and structure. Here is another example of returning multiple values from a Python function.

from collections import namedtuple

def get_point():
    Point = namedtuple('Point', 'x y')
    return Point(10, 20)

point = get_point()
print(point)  # Output: Point(x=10, y=20)
print(point.x, point.y)  # Output: 10 20

Here, the get_point function returns a named tuple, which makes accessing the values more intuitive.

Check out Python Function Naming Conventions

Python Function Return Multiple Values – Examples

Now, let me show you a few real examples of returning multiple values from a function in Python.

Scenario 1: Returning Multiple Calculations

Imagine you’re building a financial application and need to calculate both the interest and the total amount for a given principal, rate, and time. Here is an example.

def calculate_interest(principal, rate, time):
    interest = (principal * rate * time) / 100
    total_amount = principal + interest
    return interest, total_amount

interest, total_amount = calculate_interest(1000, 5, 2)
print(f"Interest: {interest}, Total Amount: {total_amount}")
# Output: Interest: 100.0, Total Amount: 1100.0

If you will execute the above Python code, you can see the output in the screenshot below:

python function return multiple values declaration

Scenario 2: Data Processing

Let me show you another real example of returning multiple values from a function in Python.

In data analysis, you might need to return both the processed data and some statistics about the data.

def process_data(data):
    processed_data = [d * 2 for d in data]
    data_sum = sum(processed_data)
    data_count = len(processed_data)
    return processed_data, data_sum, data_count

data = [1, 2, 3, 4, 5]
processed_data, data_sum, data_count = process_data(data)
print(f"Processed Data: {processed_data}, Sum: {data_sum}, Count: {data_count}")
# Output: Processed Data: [2, 4, 6, 8, 10], Sum: 30, Count: 5

Scenario 3: User Authentication

In a web application, you might need to return both the authentication status and the user profile. Here is an example and the complete Python code.

def authenticate_user(username, password):
    if username == "admin" and password == "secret":
        return True, {"username": "admin", "role": "administrator"}
    else:
        return False, {}

is_authenticated, user_profile = authenticate_user("admin", "secret")
print(f"Authenticated: {is_authenticated}, User Profile: {user_profile}")
# Output: Authenticated: True, User Profile: {'username': 'admin', 'role': 'administrator'}

Here is the output in the screenshot below:

python function return multiple values type

Conclusion

In this tutorial, I have explained how to return multiple values from a function in Python using tuples, lists, dictionaries, named tuples, etc. We also saw different real examples of returning multiple values from Python functions.

You may also like:

Leave a Comment