Unpacking Multiple Return Values into Variables
In this lesson, you will learn how to efficiently capture and assign multiple return values from a function to individual variables using Python’s elegant tuple unpacking syntax.
From Packing to Unpacking
Previously, you learned that when you return multiple values from a function, Python automatically "packs" them into a single data structure called a tuple. For example, if you write return x, y, Python hands back a single tuple containing both values.
To use those values individually, you don’t need to access them by index (like result[0]). Instead, you can "unpack" them directly into separate variables in a single line. This makes your code much cleaner and easier to read.
The Mechanics of Unpacking
Imagine a function that calculates both the area and the perimeter of a rectangle. Instead of returning a tuple and then manually pulling the items out, you can list the variables you want to assign on the left side of the assignment operator:
def get_rectangle_stats(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter # Packing the return values
# Unpacking the tuple into two distinct variables
rect_area, rect_perimeter = get_rectangle_stats(10, 5)
print(f"Area: {rect_area}")
print(f"Perimeter: {rect_perimeter}")
In the line rect_area, rect_perimeter = get_rectangle_stats(10, 5), Python looks at the tuple returned by the function and maps the first value to rect_area and the second to rect_perimeter.
Why This Matters
This pattern allows you to bypass the need for intermediate "container" variables. It communicates your intentions clearly: you expect exactly two pieces of information, and you are ready to use them immediately. Just remember: the number of variables on the left must exactly match the number of values returned by the function, or Python will raise a ValueError.
Key Takeaway: You can assign multiple values returned from a function to individual variables by placing a comma-separated list of variable names on the left side of your assignment, effectively "unpacking" the tuple in one step.