Skip to content

Python: Return Multiple Values from a Function

Python Return Multiple Values from Function Cover Image

In this tutorial, you’ll learn how to use Python to return multiple values from your functions. This is a task that is often quite difficult in some other languages, but very easy to do in Python.

You’ll learn how to use tuples, implicitly or explicitly, lists, and dictionaries to return multiple values from a function. You’ll also learn how to identify which method is best suited for your use case. You’ll also learn how to unpack items of unequal length, using the unpacking operator (*).

Being able to work with functions is an incredibly useful skill that allows you to more readily follow the DRY (don’t repeat yourself) principle. Functions allow your code to be significantly more readable and less repetitive. All of this allows your code to be more maintainable and reduces complexity of the code.

The Quick Answer: Use Tuple Unpacking

Quick Answer - Python Return Multiple Values from Function

How do Functions Return Values in Python?

Python functions are easy ways to structure code into dynamic processes that are readable and reusable. While Python functions can accept inputs, in this tutorial, we’ll be looking at function outputs. Specifically, we’ll be look at how functions return values.

Let’s take a look at how a function in Python is designed and how to return one value and how to return two values.

# Defining Simple Functions to Return One and Two Values

def return_one():
    return 'x'

def return_two():
    return 'x', 'y'

In the example above, we have defined two different functions, return_one() and return_two(). The former of these returns only a single value. Meanwhile, the latter function, return_two(), returns two values. This is done by separating the values by commas.

In the next section, you’ll learn how and why returning multiple values actually works.

Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.

How to Return Multiple Values from a Python Function with Tuples

In the previous section, you learned how to configure a Python function to return more than a single value.

The way that this works, is that Python actually turns the values (separated by commas) into a tuple. We can see how this works by assigning the function to a variable and checking its type.

# Returning Multiple Values with Tuples
def return_multiple():
    return 1, 2, 3

variable = return_multiple()
print(type(variable))

# Returns: <class 'tuple'>

We can see in the code above that when we assign our function to a variable, that a tuple is generated.

This may surprise you, however, since you don’t actually tell the function to return (1, 2, 3). Python implicitly handles converting the return values into a tuple. It’s not the parentheses that turn the return value into a tuple, but rather the comma along with the parentheses.

We can verify this by checking the type of the value (1), for example. This returns: int.

>>> print(type((1))
<class 'int'>

Again, this might surprise you. If we changed our value to (1,), however, we return a different result.

>>> print(type((1,))
<class 'tuple'>

A lot of this may seem like semantics, but it allows you to understand why these things actually work. Now, let’s learn how to assign these multiple variables to different variables.

Let’s look at the same function as before. Instead of assigning the return values to a single tuple, let’s unpack our tuple and return three separate values.

# Returning Multiple Values with Direct Assignment

def return_multiple():
    return 1, 2, 3

a, b, c = return_multiple()
print(a)
print(b)
print(c)

# Returns: 
# 1
# 2
# 3

The reason this works is that Python is handling unpacking these values for us. Because we have the same number of assignment variables as we do values in the return statement, Python handles the assignment of these values for us.

In the next section, you’ll learn how to unpack multiple values from a Python to variables with mismatched lengths.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

How to Unpack Multiple Values from a Python Function to Unequal Lengths

In the example above, you learned how to return multiple values from a Python function by unpacking values from the return tuple.

There may be many times when your function returns multiple values, but you only care about a few. You don’t really care about the other values, but Python will not let you return only a few of them.

Let’s see what this looks like:

def return_multiple():
    return 1, 2, 3

a, b = return_multiple()

# Raises
# ValueError: too many values to unpack (expected 2)

This happens because our assignment needs to match the number of items returned.

However, Python also comes with an unpacking operator, which is denoted by *. Say that we only cared about the first item returned. We still need to assign the remaining values to another variable, but we can easily group them into a single variable, using the unpacking operator.

Let’s see how this works in Python:

# Returning Multiple Values of Different Length Variables

def return_multiple():
    return 1, 2, 3

a, *b = return_multiple()

print(f'{a=}')
print(f'{b=}')

# Returns:
# a=1
# b=[2, 3]

Here, we have unpacked the first value to our variable a, and all other variables to the variable b, using the notation of *b.

In the next section, you’ll learn how to return multiple values from a Python function using lists.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

How to Return Multiple Values from a Python Function with Lists

Similar to returning multiple values using tuples, as shown in the previous examples, we can return multiple values from a Python function using lists.

One of the big differences between Python sets and lists is that lists are mutable in Python, meaning that they can be changed. If this is an important characteristic of the values you return, then this is a good way to go.

Let’s see how we can return multiple values from a function, using both assignment to a single variable and to multiple variables.

# Returning Multiple Values to Lists

def return_multiple():
    return [1, 2, 3]

# Return all at once
return_all = return_multiple()

# Return multiple variables
a, b, c = return_multiple()

print(f'{return_all=}')
print(f'{a=}')
print(f'{b=}')
print(f'{c=}')

# Returns:
# return_all=[1, 2, 3]
# a=1
# b=2
# c=3

In the next section, you’ll learn how to use Python dictionaries to better understand return values.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

How to Return Multiple Values from a Python Function with Dictionaries

In both examples above, if you’re returning all values to a single variable, it can be difficult to determine what each value represents. For example, while you can access all the items in a tuple or in a list using indexing, it can be difficult to determine what each value represents.

Let’s take a look at a more complicated function that creates variables for speed, time, and distance travelled for a car.

If we returned this as a tuple or as a list, then we would need to know which variable represents what item. However, we can also return these items as a dictionary. When we do this, we can access each item by its key.

Let’s see how we can do this in Python:

# Returning Multiple Values using a Dictionary

def calculate_distance(speed_of_car, time_travelled):
    distance_travelled = speed_of_car * time_travelled
    return {'speed': speed_of_car, 'time': time_travelled, 'distance': distance_travelled}

items = calculate_distance(10, 60)
print(f'distance = {items.get("distance")}')
print(f'speed = {items.get("speed")}')

# Returns:
# distance = 600
# speed = 10

Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

Conclusion

In this tutorial, you learned how to return multiple values from Python functions. You learned how and why multiple values can be returned and how to optimize how values are returned for your use cases, by learning how to return tuples, lists, and dictionaries. You also learned how to unpack multiple values to variables of different lengths.

To learn more about Python functions, check out the official documentation here.

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Tags:

1 thought on “Python: Return Multiple Values from a Function”

  1. Pingback: Functions in Python • datagy

Leave a Reply

Your email address will not be published. Required fields are marked *