Returning Multiple Values from Python Functions: Tuple Auto-Packing and Unpacking

In many programming languages, a function can basically return only one value. If you want to return multiple values, you usually have to pack them into an array or an object. However, in Python, you can easily return multiple values simply by separating them with commas (,).

This article explains the mechanism of returning multiple values from a function and the method called “Unpacking” to receive them.


目次

Mechanism of Returning Multiple Values

When you write return a, b in a Python function, Python internally groups (packs) these values into a single data structure called a Tuple. In other words, while it looks like it is returning multiple values, it is actually returning “one tuple object.”

Specific Code Example

As an example, let’s create a function that accepts the “width” and “height” of a rectangle and calculates both its “area” and “perimeter” at the same time.

def calculate_rectangle_properties(width, height):
    """
    Function to calculate area and perimeter from width and height.
    """
    # Calculate Area
    area = width * height
    
    # Calculate Perimeter: (width + height) * 2
    perimeter = (width + height) * 2
    
    # Return two values separated by a comma (Returned as a tuple)
    return area, perimeter

# --- Execution ---

# Define size
rect_width = 5
rect_height = 8

# Call the function
result = calculate_rectangle_properties(rect_width, rect_height)

print(f"Return Value: {result}")
print(f"Type of Return Value: {type(result)}")

Output:

Return Value: (40, 26)
Type of Return Value: <class 'tuple'>

As you can see, the return value is a tuple (40, 26).


How to Receive Return Values (Unpacking)

If you want to handle the values returned as a tuple as separate variables, use the feature called Unpacking. This is the recommended way to receive values in Python. Simply prepare the same number of variables on the left side of the assignment as there are return values, and they will be automatically decomposed and assigned.

# Unpack the return values into area_val and perimeter_val
area_val, perimeter_val = calculate_rectangle_properties(10, 20)

print(f"Area: {area_val}")
print(f"Perimeter: {perimeter_val}")

Output:

Area: 200
Perimeter: 60

Ignoring Unnecessary Return Values (Underscore _)

If a function returns multiple values but you only need some of them, it is a convention to use an underscore _ for the variable name. This explicitly indicates “I am intentionally not using this value.”

# When you only need the area and don't need the perimeter
area_only, _ = calculate_rectangle_properties(6, 6)

print(f"Square Area: {area_only}")
# '_' contains the perimeter, but we won't use it in subsequent processing

Output:

Square Area: 36

Summary

  • Python functions can return multiple values simply by writing return val1, val2.
  • Internally, they are returned as a tuple.
  • It is common to unpack values into individual variables at the caller side like var1, var2 = func().
  • If there are unwanted values, receive them with _ to clarify the intent of your code.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次