Course contentsShow
← Python
Lesson 152 of 1,0603. Functions and ModularizationFree lesson

Returning Multiple Values via Tuple Packing

You will master the technique of returning multiple data points from a single function call by using Python's implicit tuple packing.

Returning Multiple Values via Tuple Packing

In this lesson, you will learn how to return several distinct pieces of data from a single function call using Python’s elegant tuple packing mechanism.

The Power of the Comma

Up until now, you have likely used the return statement to send a single value back to where the function was called. However, Python allows you to return multiple items at once simply by separating them with commas.

When you write return x, y, Python automatically "packs" those values into a single object called a tuple. A tuple is essentially an immutable, ordered collection of items. Because Python handles this packing for you, you don't need to manually create a list or a dictionary just to move data out of your function.

A Concrete Example

Imagine you are writing a function that calculates both the area and the perimeter of a rectangle. Instead of running two separate functions, you can compute both and return them together:

def get_rectangle_stats(width, height):
    area = width * height
    perimeter = 2 * (width + height)
    return area, perimeter  # Tuple packing happens here

# Receive the values
stats = get_rectangle_stats(5, 10)

print(stats)           # Output: (50, 30)
print(stats[0])        # Output: 50 (Area)
print(stats[1])        # Output: 30 (Perimeter)

When get_rectangle_stats(5, 10) is called, the function returns a single tuple (50, 30). You can store this tuple in one variable (as shown above) or "unpack" it directly into separate variables using assignment:

area, perimeter = get_rectangle_stats(5, 10)

print(f"The area is {area} and the perimeter is {perimeter}.")

By separating the values with a comma in the return statement, you create a clean, readable way to bundle related data points together, making your functions significantly more efficient and modular.

Key Takeaway: By placing a comma between multiple values in a return statement, Python implicitly packs them into a single tuple, allowing you to return and capture multiple data points in one move.