What actually happens when returning multiple values in a function?


#1

Question

In the context of this exercise, what actually happens when returning multiple values in a function?

Answer

In Python, when returning multiple values separated by commas, all the values listed are actually wrapped inside a data type known as a tuple, which looks like (1, 2, 3). That tuple is returned, containing each value.

This is also useful because you can do what is known as “tuple unpacking” – if a tuple has multiple values, you can assign the same number of variables to the number of elements in the tuple, so that each variable is assigned to each value in the order they appear in the tuple.

Example

# This is a simple tuple unpacking.
# Each variable is assigned to each 
# corresponding value.
arg1, arg2, arg3 = (1, 2, 3)

# This is a function that returns multiple values.
def times_ten(a, b, c):
  a = a * 10
  b = b * 10
  c = c * 10
  return a, b, c # This will return a tuple containing the values listed.

# Each variable will be assigned to each value in the returned tuple,
# in the order they appear.
new_a, new_b, new_c = times_ten(5, 6, 7)

# new_a = 50
# new_b = 60
# new_c = 70