How to Return Multiple Values in Python
Table of Contents
A Python function can return more than one value by separating them with commas.
All the content from our Boot.dev courses are available for free here on the blog. This one is from the "Functions" chapter of Learn Python for Beginners. If you want to try the far more immersive version of the course, do check it out!
Return Multiple Values From a Function
Separate the values in the return statement with commas:
def cast_iceblast(wizard_level, start_mana):
damage = wizard_level * 2
new_mana = start_mana - 10
return damage, new_mana # return two values
Receiving Multiple Values
When calling a function that returns multiple values, you can assign them to multiple variables.
damage, mana = cast_iceblast(5, 100)
print(f"Damage: {damage}, Remaining Mana: {mana}")
# Damage: 10, Remaining Mana: 90
When cast_iceblast is called, it returns two values. The first value is assigned to damage, and the second value is assigned to mana.
Return Value Order Matters
Just like function inputs, it's the order of the values that matters, not the variable names. We could just as easily have named the variables one and two:
one, two = cast_iceblast(5, 100)
print(f"Damage: {one}, Remaining Mana: {two}")
# Damage: 10, Remaining Mana: 90
Descriptive variable names make your code easier to understand, so name them well!
The damage and new_mana variables from cast_iceblast's function body only exist inside of the function. They can't be used outside of the function. The Python functions guide covers that behavior in its section on scope.
Frequently Asked Questions
Can a Python function return multiple values?
Yes. Separate the values with commas in the return statement, then assign them to multiple variables when calling the function.
How do you receive multiple return values?
Assign the function call to multiple variables separated by commas.
Does the order of multiple return values matter?
Yes. The first returned value goes to the first variable, the second to the second variable, and so on. Variable names do not affect the order.
Can variables inside the function be used outside it?
No. Local variables from the function body only exist inside the function, but their returned values can be assigned to variables outside it.
