HomeCourseModule 05 › Returning multiple values & unpacking

Returning multiple values & unpacking

Module 05 · Functions6 min readBeginner

What you'll learn

  • Return multiple values as a tuple
  • Unpack a return into multiple variables
  • Decide between a tuple return and a dict return

The tuple return

def split_full_name(full):
    first, last = full.split(" ", 1)
    return first, last

f, l = split_full_name("Alice Smith")
print(f)   # Alice
print(l)   # Smith

Behind the scenes, returning first, last is the same as returning the tuple (first, last). The parentheses are optional.

Unpacking

name, age, role = ("Alice", 32, "analyst")

The dict return — when there are many fields

def summary(numbers):
    return {
        "count": len(numbers),
        "total": sum(numbers),
        "mean":  sum(numbers) / len(numbers),
        "max":   max(numbers),
        "min":   min(numbers),
    }

stats = summary([10, 20, 30, 40, 50])
print(stats["mean"])   # 30.0

Better than returning a 5-tuple: at the call site you read stats["mean"], not stats[2].

💡 Rule of thumb
Two return values → tuple. Three or more → dict (or a class, which we won't need in this course).

Key takeaways

  • Return multiple values as a tuple: return a, b.
  • Unpack at the call site: x, y = func().
  • For many fields, return a dict — readability wins.

min_max_avg

Write a function that takes a list of numbers and returns min, max, and average. Try a tuple return first; then rewrite as a dict.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.