13.4. Tuples as Return Values

Functions can return tuples as return values. This is very useful — we often want to know some batsman’s highest and lowest score, or we want to find the mean and the standard deviation, or we want to know the year, the month, and the day, or if we’re doing some ecological modeling we may want to know the number of rabbits and the number of wolves on an island at a given time. In each case, a function (which can only return a single value), can create a single tuple holding multiple elements.

For example, we could write a function that returns both the area and the circumference of a circle of radius r.

Again, we can take advantage of packing to make the code look a little more readable on line 4

It’s common to unpack the returned values into multiple variables.

Check your Understanding

    If you want a function to return two values, contained in variables x and y, which of the following methods will work?

  • Make the last two lines of the function be "return x" and "return y"
  • As soon as the first return statement is executed, the function exits, so the second one will never be executed; only x will be returned
  • Include the statement "return [x, y]"
  • return [x,y] is not the preferred method because it returns x and y in a mutable list rather than a tuple which is more efficient. But it is workable.
  • Include the statement "return (x, y)"
  • return (x, y) returns a tuple.
  • Include the statement "return x, y"
  • return x, y causes the two values to be packed into a tuple.
  • It's not possible to return two values; make two functions that each compute one value.
  • It is possible, and frequently useful, to have one function compute multiple values.

Define a function called information that takes as input, the variables name, birth_year, fav_color, and hometown. It should return a tuple of these variables in this order.

Define a function called info with the following required parameters: name, age, birth_year, year_in_college, and hometown. The function should return a tuple that contains all the inputted information.

You have attempted of activities on this page