4. Return a tuple

A function can return more than one value. Separate the values with commas and Python packs them into a tuple. return a, b is the same as return (a, b):

  • The caller receives a single tuple, not two separate values.
  • Parentheses are optional around the returned values.
  • The caller can keep the tuple as one value or unpack it: x, y = coordinates().
  • Unpacking assigns each item to its own variable in one step.

Coming from JavaScript? Returning a, b does not build an array: the caller receives a tuple, which can be unpacked like const [x, y] = fn(). To return one object, return a dict.

#01

Define a function that returns a tuple

Define a function named dimensions with no parameters. It must return the tuple (1920, 1080). Call it inside print().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Return several values

A comma between returned values packs them into a tuple; you do not need parentheses. Define stats with no parameters and return 10, 20 from it. Print the result of calling stats().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Build a tuple from parameters

Define min_max(a, b) with two parameters. If a < b, return a, b; otherwise return b, a. Print min_max(5, 2).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Unpack the result of a call

A function call that returns a tuple can be unpacked directly. Define min_max(a, b) as in the previous exercise, then unpack min_max(8, 3) into low and high in one assignment. Print low, then high.

Print exactly:

Create a free account to save your progress and unlock chapter 2.