How to return multiple values from a Python function
Published on Aug. 22, 2023, 12:20 p.m.
To return multiple values from a Python function, you can pack the values into a tuple and return the tuple. Here’s an example:
def get_player_info(player_id):
# assume we have some code that gets player info using player_id
name = "John"
score = 100
level = 5
return name, score, level
In this example, we define a function called get_player_info
that takes a player_id
argument and returns three pieces of information about the player: their name, score, and level. We pack these three values into a tuple using parentheses, and return the tuple.
To call this function and extract the values from the returned tuple, we can use tuple unpacking:
player_name, player_score, player_level = get_player_info(123)
In this line of code, we call get_player_info
with an argument of 123, and assign the three values returned by the function to the variables player_name
, player_score
, and player_level
using tuple unpacking.
Note that if you want to return multiple values of different types, using a dictionary or a named tuple might be a better option than a tuple.
When returning multiple values from a Python function, using a tuple or a dictionary to pack the values is a common approach. Here are some advantages and disadvantages to consider:
Advantages:
- Easier to return multiple values of different types compared to using a global variable or an object with instance variables.
- More concise and can improve the readability of the code compared to assigning multiple variables inside the function and returning a single value.
- Can make it easier to group multiple related values together and can improve the maintainability and scalability of the code.
Disadvantages:
- Potential for errors in unpacking the tuple or dictionary returned by the function when calling it.
- If the function is used often and the returned values are complex, extracting values from the tuple or dictionary repeatedly could slow down the code.
- Can make the code harder to read if the tuple/dictionary contains many values, so it’s important to balance readability and functionality.
Overall, returning multiple values using a tuple or dictionary is a useful technique in Python, and its use depends on the specific requirements of the code and personal preference.