How to Return Multiple Values from a Python Function
This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.
Python code
12 linesdef get_user_stats(name, score, level):
"""Return multiple values as a tuple."""
return name, score, level
if __name__ == "__main__":
result = get_user_stats("Alice", 95, 3)
print(result)
print(type(result))
# Unpacking into individual variables
player_name, player_score, player_level = result
print(f"{player_name}: score={player_score}, level={player_level}")
Output
('Alice', 95, 3)
<class 'tuple'>
Alice: score=95, level=3
How it works
In Python, when you list values separated by commas after return, they are automatically packed into a tuple. The return name, score, level statement returns a tuple (name, score, level). Functions that return a tuple allow you to convey multiple related pieces of data without creating a custom class. The unpacking assignment player_name, player_score, player_level = result splits the tuple into individual variables, making the code more readable. This pattern works because the number of variables on the left matches the tuple length.
Common mistakes
- Forgetting that the return type is a tuple and trying to treat it as a single value.
- Trying to unpack into a different number of variables than the tuple length, which raises a ValueError.
- Using a mutable list instead of a tuple when immutability is desired.
Variations
- Use a namedtuple from the collections module for named fields.
- Use a dataclass for more complex return data.
- Return a dictionary to have named access to the values.
Real-world use cases
- A function that returns both the result and an error code to handle success/failure.
- A data processing function that returns the updated record and the number of changes made.
- A business logic function that returns the order total and the calculated tax for invoice generation.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.