Skip to content

Module 9 · Functions — topic 12 of 19

Multiple return values

Returning several results as a tuple, unpacking them in the caller, ignoring values with _, and when to return a dictionary or named tuple instead.

Beginner 8 min read·Lesson 137 of 306 in Python Programming

Learning objectives

  • Return and unpack several values
  • Ignore unneeded values with _
  • Choose between tuples, dictionaries and named tuples for results

Definition

A Python function returns one object, but return a, b builds a tuple (a, b), so a function can effectively return several values that the caller unpacks with a, b = f().

Introduction

divmod(17, 5) returns (3, 2): a quotient and a remainder in one call. Your functions can do the same with return q, r.

Why it matters

Many calculations naturally produce more than one result — minimum and maximum, success and message, latitude and longitude. Returning them together avoids computing twice or using global variables.

Detailed explanation

return a, b creates a tuple; the parentheses are optional.

The caller unpacks with low, high = min_max(values). The number of names must match the number of items, otherwise ValueError.

Use _ for values you don't need: _, remainder = divmod(17, 5).

Starred unpacking collects the rest: first, *others = scores.

When results have meaning beyond their position, return a dictionary or a collections.namedtuple / dataclass so callers can access result.minimum instead of result[0].

A common pattern for operations that can fail is to return a pair such as (success, message) or (value, error). It keeps the happy path and the failure details together, and the caller can unpack and branch on the first item. For genuinely exceptional situations, raising an exception (module 12) is usually better, because a caller can't accidentally ignore it the way they can ignore a returned flag.

Syntax

Python
def min_max(values):
return min(values), max(values)
low, high = min_max([4, 9, 1])
_, remainder = divmod(17, 5)
  • return a, b returns a tuple.
  • Unpack with matching names.
  • _ ignores a value.

Code examples

Return two values

Python
def min_max(values):
return min(values), max(values)
low, high = min_max([4, 9, 1, 7])
print(low, high)
result = min_max([3, 3])
print(result, type(result).__name__)
Output
1 9
(3, 3) tuple

Ignoring and collecting

Python
quotient, _ = divmod(17, 5)
print(quotient)
first, *rest = [90, 75, 60, 45]
print(first, rest)
Output
3
90 [75, 60, 45]

More examples

Named results

Python
from collections import namedtuple
Stats = namedtuple("Stats", "count mean minimum maximum")
def describe(values):
return Stats(len(values), round(sum(values) / len(values), 2), min(values), max(values))
def validate(password):
if len(password) < 8:
return False, "too short"
if password.isalpha():
return False, "add a digit or symbol"
return True, "ok"
s = describe([72, 95, 58, 81])
print(s)
print(s.mean, s.maximum - s.minimum)
for pw in ["abc", "password", "pass1234"]:
ok, message = validate(pw)
print(pw, ok, message)
Output
Stats(count=4, mean=76.5, minimum=58, maximum=95)
76.5 37
abc False too short
password False add a digit or symbol
pass1234 True ok

Step-by-step explanation

  • namedtuple creates a tuple type whose items also have names.
  • describe returns one Stats object, readable as s.mean instead of s[1].
  • validate returns a (bool, message) pair, unpacked into ok and message in the loop.

Expected output

Running “Named results” prints exactly:

TextOutput
Stats(count=4, mean=76.5, minimum=58, maximum=95)
76.5 37
abc False too short
password False add a digit or symbol
pass1234 True ok

Practical applications

  • divmod, os.path.split and str.partition return tuples.
  • Validation helpers commonly return (is_valid, error_message).

Best practices

  • Return at most two or three values as a plain tuple.
  • Use named tuples or dataclasses for richer results.
  • Unpack immediately into well-named variables.

Common mistakes

Wrong number of names

Avoid

low, high = min_max(v), 0

Prefer

low, high = min_max(v)

Unpacking needs exactly as many names as items; otherwise ValueError (or here, a nested tuple).

Too many positional results

Avoid

return a, b, c, d, e, f # what is item 4?

Prefer

return Stats(...) # named fields

Long tuples are unreadable; name the fields.

Important notes

  • Dataclasses (module 17) are another clear way to return structured results.

Key takeaways

  • return a, b returns a tuple.
  • Unpack with matching names; use _ to ignore.
  • Name fields when results have meaning.

Try it yourself

  1. 1
    Write split_name(full) that returns (first, last) and handles single names.
  2. 2
    Return the count, sum and average of a list as a namedtuple.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic