Returning Multiple Values from Functions

🏷️ Tuples and Sets / Tuples: Immutable Sequences

One of the most practical features in Python is the ability to return multiple values from a single function. This might seem unusual if you're coming from other programming languages, but Python makes it incredibly clean and intuitive. Instead of packaging results into a complex object or using output parameters, you can simply return several values separated by commas.


⚙️ How It Works

When you return multiple values separated by commas, Python automatically packs them into a tuple. The calling code can then unpack these values into separate variables.

  • A function can return any number of values using a comma-separated list after the return keyword.
  • The returned object is always a single tuple containing all the values.
  • The caller can "unpack" the tuple directly into individual variables.

🛠️ Basic Example: Returning Two Values

Consider a function that performs a calculation and returns both the result and a status flag:

  • Function definition: def divide(a, b):
    Inside the function: result = a / b and status = "success"
    Return statement: return result, status

  • Calling the function: quotient, message = divide(10, 3)
    Now quotient holds 3.333... and message holds "success"

  • If you call the function and assign it to a single variable: output = divide(10, 3)
    Then output is a tuple: (3.333..., "success")


📊 Returning Three or More Values

You are not limited to just two values. You can return as many as you need:

  • Function example: def get_user_stats(name, score):
    Returns: return name, score, score * 2, score > 50

  • Calling it: user, current_score, double_score, is_high = get_user_stats("Alice", 75)
    Each variable gets its corresponding value from the returned tuple.

  • This approach is especially useful when a function needs to communicate multiple pieces of information without creating a custom class or dictionary.


🕵️ Ignoring Unwanted Return Values

Sometimes you only need a subset of the returned values. Python provides a convention using an underscore (_) to ignore specific values:

  • Function returning three values: def get_coordinates():
    Returns: return 10.5, 20.3, 15.8 (x, y, z)

  • Ignoring the z-coordinate: x, y, _ = get_coordinates()
    The underscore acts as a placeholder, and the z value is discarded.

  • Ignoring multiple values: x, *_ = get_coordinates()
    The asterisk (*) collects all remaining values into a list, which you can also ignore.


📋 Comparison: Returning Multiple Values vs. Other Approaches

Approach Example Pros Cons
Multiple return values return a, b, c Clean syntax, automatic unpacking, no extra code Order matters when unpacking
Return a list return [a, b, c] Can be modified later, index-based access Less readable, requires indexing
Return a dictionary return {"x": a, "y": b} Named access, order doesn't matter More verbose, slower access
Return a custom object return Result(a, b) Type safety, named attributes Requires class definition

🛠️ Practical Example: System Resource Check

Here's a realistic scenario where returning multiple values is extremely handy:

  • Function: def check_system_resources():
    Inside, it gathers CPU usage, memory usage, and disk usage.
    Returns: return cpu_percent, memory_percent, disk_percent

  • Calling the function:
    cpu, mem, disk = check_system_resources()
    Now you have three separate variables with meaningful names.

  • Using the values:
    if cpu > 90: print("CPU overload detected")
    if mem > 85: print("Memory running low")
    if disk > 95: print("Disk space critical")

  • This pattern keeps your code clean and avoids the need to access indices or dictionary keys.


⚙️ Swapping Values Using Tuple Unpacking

A classic Python trick that leverages multiple return values is swapping variables without a temporary variable:

  • Traditional approach (other languages):
    temp = a
    a = b
    b = temp

  • Python approach:
    a, b = b, a
    Python evaluates the right side as a tuple (b, a) and unpacks it directly into a and b.

  • This works because the right side is evaluated completely before any assignment happens.


🕵️ Common Pitfalls to Avoid

  • Forgetting to unpack: If you assign the result to a single variable, you get a tuple, not individual values. Always check whether you need to unpack or access by index.

  • Mismatched number of variables: If your function returns three values but you try to unpack into two variables, Python raises a ValueError. Always match the number of variables to the number of returned values.

  • Modifying returned tuples: Remember that tuples are immutable. If you need to modify a returned collection, consider returning a list instead, or convert the tuple to a list after receiving it.


📊 Summary

Returning multiple values from functions is a powerful Python feature that makes your code more readable and expressive. By simply separating values with commas in the return statement, you can communicate complex results without extra boilerplate. Combined with tuple unpacking, this pattern allows for clean, intuitive code that is easy to maintain and understand.


A function in Python can return multiple values at once by packing them into a tuple, which the caller can then unpack into separate variables.

🔧 Example 1: Returning two values as a tuple

A function returns two values separated by a comma, which Python automatically packs into a tuple.

def get_coordinates():
    x = 10
    y = 20
    return x, y

result = get_coordinates()
print(result)

📤 Output: (10, 20)


🔧 Example 2: Unpacking returned values into separate variables

The caller can unpack the returned tuple directly into individual variables.

def get_dimensions():
    width = 800
    height = 600
    return width, height

w, h = get_dimensions()
print("Width:", w)
print("Height:", h)

📤 Output: Width: 800
📤 Output: Height: 600


🔧 Example 3: Returning three values from a calculation

A function computes and returns multiple results from a single operation.

def calculate_circle(radius):
    pi = 3.14159
    diameter = 2 * radius
    circumference = 2 * pi * radius
    area = pi * radius * radius
    return diameter, circumference, area

d, c, a = calculate_circle(5)
print("Diameter:", d)
print("Circumference:", round(c, 2))
print("Area:", round(a, 2))

📤 Output: Diameter: 10
📤 Output: Circumference: 31.42
📤 Output: Area: 78.54


🔧 Example 4: Returning values with different data types

A function can return a mix of strings, numbers, and booleans in a single return statement.

def analyze_number(num):
    is_positive = num > 0
    is_even = num % 2 == 0
    absolute_value = abs(num)
    return is_positive, is_even, absolute_value

positive, even, abs_val = analyze_number(-7)
print("Positive:", positive)
print("Even:", even)
print("Absolute:", abs_val)

📤 Output: Positive: False
📤 Output: Even: False
📤 Output: Absolute: 7


🔧 Example 5: Practical use — splitting a full name

A function parses a full name string and returns the first and last names separately.

def split_name(full_name):
    parts = full_name.split(" ")
    first_name = parts[0]
    last_name = parts[1]
    return first_name, last_name

first, last = split_name("Ada Lovelace")
print("First name:", first)
print("Last name:", last)

📤 Output: First name: Ada
📤 Output: Last name: Lovelace


📊 Comparison Table

Feature Single Return Value Multiple Return Values
Syntax return value return value1, value2
Data type returned Any single type Tuple (packed automatically)
Unpacking required No Yes, or access by index
Common use case Simple result Multiple related results
Readability Straightforward Clear when values are related

One of the most practical features in Python is the ability to return multiple values from a single function. This might seem unusual if you're coming from other programming languages, but Python makes it incredibly clean and intuitive. Instead of packaging results into a complex object or using output parameters, you can simply return several values separated by commas.


⚙️ How It Works

When you return multiple values separated by commas, Python automatically packs them into a tuple. The calling code can then unpack these values into separate variables.

  • A function can return any number of values using a comma-separated list after the return keyword.
  • The returned object is always a single tuple containing all the values.
  • The caller can "unpack" the tuple directly into individual variables.

🛠️ Basic Example: Returning Two Values

Consider a function that performs a calculation and returns both the result and a status flag:

  • Function definition: def divide(a, b):
    Inside the function: result = a / b and status = "success"
    Return statement: return result, status

  • Calling the function: quotient, message = divide(10, 3)
    Now quotient holds 3.333... and message holds "success"

  • If you call the function and assign it to a single variable: output = divide(10, 3)
    Then output is a tuple: (3.333..., "success")


📊 Returning Three or More Values

You are not limited to just two values. You can return as many as you need:

  • Function example: def get_user_stats(name, score):
    Returns: return name, score, score * 2, score > 50

  • Calling it: user, current_score, double_score, is_high = get_user_stats("Alice", 75)
    Each variable gets its corresponding value from the returned tuple.

  • This approach is especially useful when a function needs to communicate multiple pieces of information without creating a custom class or dictionary.


🕵️ Ignoring Unwanted Return Values

Sometimes you only need a subset of the returned values. Python provides a convention using an underscore (_) to ignore specific values:

  • Function returning three values: def get_coordinates():
    Returns: return 10.5, 20.3, 15.8 (x, y, z)

  • Ignoring the z-coordinate: x, y, _ = get_coordinates()
    The underscore acts as a placeholder, and the z value is discarded.

  • Ignoring multiple values: x, *_ = get_coordinates()
    The asterisk (*) collects all remaining values into a list, which you can also ignore.


📋 Comparison: Returning Multiple Values vs. Other Approaches

Approach Example Pros Cons
Multiple return values return a, b, c Clean syntax, automatic unpacking, no extra code Order matters when unpacking
Return a list return [a, b, c] Can be modified later, index-based access Less readable, requires indexing
Return a dictionary return {"x": a, "y": b} Named access, order doesn't matter More verbose, slower access
Return a custom object return Result(a, b) Type safety, named attributes Requires class definition

🛠️ Practical Example: System Resource Check

Here's a realistic scenario where returning multiple values is extremely handy:

  • Function: def check_system_resources():
    Inside, it gathers CPU usage, memory usage, and disk usage.
    Returns: return cpu_percent, memory_percent, disk_percent

  • Calling the function:
    cpu, mem, disk = check_system_resources()
    Now you have three separate variables with meaningful names.

  • Using the values:
    if cpu > 90: print("CPU overload detected")
    if mem > 85: print("Memory running low")
    if disk > 95: print("Disk space critical")

  • This pattern keeps your code clean and avoids the need to access indices or dictionary keys.


⚙️ Swapping Values Using Tuple Unpacking

A classic Python trick that leverages multiple return values is swapping variables without a temporary variable:

  • Traditional approach (other languages):
    temp = a
    a = b
    b = temp

  • Python approach:
    a, b = b, a
    Python evaluates the right side as a tuple (b, a) and unpacks it directly into a and b.

  • This works because the right side is evaluated completely before any assignment happens.


🕵️ Common Pitfalls to Avoid

  • Forgetting to unpack: If you assign the result to a single variable, you get a tuple, not individual values. Always check whether you need to unpack or access by index.

  • Mismatched number of variables: If your function returns three values but you try to unpack into two variables, Python raises a ValueError. Always match the number of variables to the number of returned values.

  • Modifying returned tuples: Remember that tuples are immutable. If you need to modify a returned collection, consider returning a list instead, or convert the tuple to a list after receiving it.


📊 Summary

Returning multiple values from functions is a powerful Python feature that makes your code more readable and expressive. By simply separating values with commas in the return statement, you can communicate complex results without extra boilerplate. Combined with tuple unpacking, this pattern allows for clean, intuitive code that is easy to maintain and understand.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

A function in Python can return multiple values at once by packing them into a tuple, which the caller can then unpack into separate variables.

🔧 Example 1: Returning two values as a tuple

A function returns two values separated by a comma, which Python automatically packs into a tuple.

def get_coordinates():
    x = 10
    y = 20
    return x, y

result = get_coordinates()
print(result)

📤 Output: (10, 20)


🔧 Example 2: Unpacking returned values into separate variables

The caller can unpack the returned tuple directly into individual variables.

def get_dimensions():
    width = 800
    height = 600
    return width, height

w, h = get_dimensions()
print("Width:", w)
print("Height:", h)

📤 Output: Width: 800
📤 Output: Height: 600


🔧 Example 3: Returning three values from a calculation

A function computes and returns multiple results from a single operation.

def calculate_circle(radius):
    pi = 3.14159
    diameter = 2 * radius
    circumference = 2 * pi * radius
    area = pi * radius * radius
    return diameter, circumference, area

d, c, a = calculate_circle(5)
print("Diameter:", d)
print("Circumference:", round(c, 2))
print("Area:", round(a, 2))

📤 Output: Diameter: 10
📤 Output: Circumference: 31.42
📤 Output: Area: 78.54


🔧 Example 4: Returning values with different data types

A function can return a mix of strings, numbers, and booleans in a single return statement.

def analyze_number(num):
    is_positive = num > 0
    is_even = num % 2 == 0
    absolute_value = abs(num)
    return is_positive, is_even, absolute_value

positive, even, abs_val = analyze_number(-7)
print("Positive:", positive)
print("Even:", even)
print("Absolute:", abs_val)

📤 Output: Positive: False
📤 Output: Even: False
📤 Output: Absolute: 7


🔧 Example 5: Practical use — splitting a full name

A function parses a full name string and returns the first and last names separately.

def split_name(full_name):
    parts = full_name.split(" ")
    first_name = parts[0]
    last_name = parts[1]
    return first_name, last_name

first, last = split_name("Ada Lovelace")
print("First name:", first)
print("Last name:", last)

📤 Output: First name: Ada
📤 Output: Last name: Lovelace


📊 Comparison Table

Feature Single Return Value Multiple Return Values
Syntax return value return value1, value2
Data type returned Any single type Tuple (packed automatically)
Unpacking required No Yes, or access by index
Common use case Simple result Multiple related results
Readability Straightforward Clear when values are related