Returning Multiple Values
Now we’ll look at how Python functions can return multiple values. In Python, a function can return multiple values using a single
return statement by simply listing those values separated by commas.
I have to say that as a programmer coming from other languages into Python, this is an amazing feature. Here’s a function that uses three functions from the
statistics module to compute and return three different measures of center in a single statement.
I’m using the same sample data that the article uses, so if you’re following along, we’ll see similar results. I create the sample data, call
describe() on that data, saving the return value to a variable, and then display its value.
01:35 The values in the tuple can be saved to different variables using iterable unpacking. You use an assignment statement—in this case, with three variables on the left-hand side because there are three elements in the returned tuple—and each value in the tuple is saved to a different variable.
02:28 When a CPU performs integer division, even if you’re asking for just the quotient or just the modulus, it usually computes both. That’s just how the algorithm works, so you might as well have a function that returns both of those values as well.
02:57 We could’ve saved this tuple to a single variable. We could have used iterable unpacking to save them to multiple variables. In this case, the left-hand side of the assignment statement would have had just two variables: one to contain the quotient and the other to contain the modulus, the remainder.
Become a Member to join the conversation.