How to Return Multiple Values from a Function in Python?

As a Python developer working on a project for one of my clients, I came across a scenario where I needed to return multiple values from a function in Python. After researching and experimenting I found three effective ways to accomplish this task. Let us learn more about this topic with suitable examples.

Return Multiple Values from a Function in Python

Python provides several ways to return multiple values from a function. We will explore the most common methods, including returning tuples, lists, dictionaries, and using the yield keyword.

Read How to Access Variables Outside a Function in Python?

1. Use Tuples

One of the simplest ways to return multiple values from a function is by using tuples. Tuples are immutable sequences in Python, which makes them ideal for returning multiple values that should not be modified.

Example: Return User Information

Let’s say we have a function that retrieves user information from a database. We want to return the user’s first name, last name, and age.

def get_user_info(user_id):
    # Simulate database query
    first_name = "John"
    last_name = "Doe"
    age = 30
    return first_name, last_name, age

# Calling the function
user_info = get_user_info(1)
print(user_info) 

# Unpacking the tuple
first_name, last_name, age = user_info
print(f"First Name: {first_name}, Last Name: {last_name}, Age: {age}")

Output:

First Name: John, Last Name: Doe, Age: 30

You can refer to the screenshot below to see the output.

Return Multiple Values from a Function in Python

In this example, the get_user_info function returns a tuple containing the user’s first name, last name, and age. We can then unpack the tuple into individual variables.

Check out How to Use Static Variables in Python Functions?

2. Use Lists

Python lists are another way to return multiple values from a function. Unlike tuples, lists are mutable, meaning you can modify their contents after they are created.

Example: Return a List of User Details

Consider a function that retrieves a list of user details.

def get_user_details(user_id):
    # Simulate database query
    details = ["John", "Doe", 30, "[email protected]"]
    return details

# Calling the function
user_details = get_user_details(1)
print(user_details) 

# Accessing individual elements
first_name = user_details[0]
last_name = user_details[1]
age = user_details[2]
email = user_details[3]
print(f"First Name: {first_name}, Last Name: {last_name}, Age: {age}, Email: {email}")

Output:

['John', 'Doe', 30, '[email protected]']
First Name: John, Last Name: Doe, Age: 30, Email: [email protected]

You can refer to the screenshot below to see the output.

Return Multiple Values from a Function in Python lists

In this example, the get_user_details function returns a list of user details. We can access individual elements using their indices.

Read How to Define a Function in Python?

3. Use Dictionaries

Dictionaries in Python allow you to return multiple values with named keys, making the code more readable and self-documenting.

Example: Return User Information as a Dictionary

Let’s modify our previous example to return user information as a dictionary.

def get_user_info_dict(user_id):
    # Simulate database query
    user_info = {
        "first_name": "John",
        "last_name": "Doe",
        "age": 30,
        "email": "[email protected]"
    }
    return user_info

# Calling the function
user_info = get_user_info_dict(1)
print(user_info)  

# Accessing individual elements
first_name = user_info["first_name"]
last_name = user_info["last_name"]
age = user_info["age"]
email = user_info["email"]
print(f"First Name: {first_name}, Last Name: {last_name}, Age: {age}, Email: {email}")

Output:

{'first_name': 'John', 'last_name': 'Doe', 'age': 30, 'email': '[email protected]'}
First Name: John, Last Name: Doe, Age: 30, Email: [email protected]

You can refer to the screenshot below to see the output.

How to Return Multiple Values from a Function in Python

In this example, the get_user_info_dict function returns a dictionary containing user information. We can access individual elements using their keys.

Check out How to Get the Name of a Function in Python?

4. Use the yield Keyword

The yield keyword allows you to return multiple values from a generator function. This is useful when you need to return a sequence of values one at a time.

Example: Generate a Sequence of User Ages

Consider a function that generates a sequence of user ages.

def generate_user_ages():
    # Simulate a sequence of user ages
    yield 25
    yield 30
    yield 35

# Calling the function
for age in generate_user_ages():
    print(age)

In this example, the generate_user_ages function uses the yield keyword to return a sequence of user ages. We can iterate over the generator to access each age.

Read How to Use the Input() Function in Python?

Use Case: Process User Data

To illustrate the practical use of returning multiple values, let’s consider a more complex example. Suppose we are developing a function that processes user data and returns multiple pieces of information, including the user’s full name, age, and status message.

def process_user_data(user_id):
    # Simulate database query
    first_name = "Jane"
    last_name = "Smith"
    age = 28

    # Process data
    full_name = f"{first_name} {last_name}"
    status_message = f"User {full_name} is {age} years old."

    return full_name, age, status_message

# Calling the function
user_data = process_user_data(1)
print(user_data)  # Output: ('Jane Smith', 28, 'User Jane Smith is 28 years old.')

# Unpacking the tuple
full_name, age, status_message = user_data
print(f"Full Name: {full_name}, Age: {age}, Status: {status_message}")

In this example, the process_user_data function processes user data and returns a tuple containing the user’s full name, age, and status message. We can then unpack the tuple into individual variables.

Check out How to Use Default Function Arguments in Python?

Conclusion

In this tutorial, I have explained how to return multiple values from a function in Python. I discussed four important methods to accomplish this they are using tuples, using lists, using dictionaries, and using yield keyword. I also discussed some use cases.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.