liveBook · Manning

Multiple return values

As explained in Python How-To

Multiple return values are values expressed by a function return statement and represented at runtime as one returned object, commonly a tuple.

When a function produces closely related results, return them together instead of creating separate functions for each result. Python packages comma-separated return expressions into one tuple object, which can then be unpacked into individual variables. section 6.2.2 section 6.2.3

Listing 6.4 Returning multiple values from a function
from statistics import mean, stdev

def generate_stats(measures):
   measure_mean = mean(measures)
   measure_std = stdev(measures)
   return measure_mean, measure_std

Return the mean and standard deviation together when both values describe the same measurements. section 6.2.2

Listing 6.5 Unpacking the return tuple object
m_mean, m_std = generate_stats(measures)

print(f"Mean: {m_mean}; SD: {m_std}")
# output: Mean: 5.6; SD: 0.8786353054595518

Unpack the returned tuple directly when both results are needed. section 6.2.3

Choose the return shape according to how the results relate:

  • Return related results together, such as a mean and standard deviation describing the same measurements. section 6.2.2
  • Split unrelated operations into separate functions; combining unrelated formatted data and calculations makes the interface harder to understand. section 6.2.2
  • Use tuple unpacking for concise access to individual returned items, or retain the tuple when treating the result as one object. section 6.2.3

How Python How-To covers it

How deep it goes
Explains tuple packing and unpacking, while stopping short of broader return-object design.
Examples
Uses a statistics function returning a mean and standard deviation, then unpacks its tuple result.
What it assumes
Assumes function calls and assignments, while explaining returned tuples and tuple unpacking.
What you can do after
Apply tuple packing and unpacking to return and consume related results from Python functions.
How it connects
Connects functions, return statements, tuples, tuple unpacking, and assignment statements.

Also explained in

Compare how 2 books explain multiple return values →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.