Most functions in Python return a value: the result of the work done by that function. But did you know that Python functions can return multiple values too? You don’t need a dictionary, list, or a class to do so.
All you need to do is list your values after the return statement, separated by commas. Here’s an example of how to return multiple values and how to assign them to multiple variables at once:
def get_user(id): # fetch user from database # .... return name, birthdate name, birthdate = get_user(4)
What we are actually doing here, is returning a tuple. We could have written
return (name, birthdate) as well, with the same effect. And if you’re wondering whether you can return more than two values this way: yes you can!
The most obvious advantage of returning multiple values using a tuple is that we can directly assign the result to multiple variables. It’s super clean and concise; just like Python was meant to be.
Alternative ways to return multiple values from a function
Using tuples this way is alright when you need to return a limited number of values. But once you get past 2 or 3 values, you should look into the usage of a data class to keep your code clean and readable.
If a data class is not an option because you’re running an older Python version, for example, you can also consider returning:
What’s best depends on the kind of data you’re returning. If the data fits in a list nicely, use a list. If the data has keys and values, use a dictionary. If your data is even more complex, you might even need to put multiple lists inside a dictionary. just remember, at some point, it will be cleaner to use a (data) class.
You can read more advanced Python function tricks in our Python functions deep dive!