Python language basics 34: returning multiple values from a function
August 1, 2015 3 Comments
Introduction
In the previous post we looked at the idea of local and global variables. We saw how a variable with function-level focus could shadow another variable with the same name but global scope. Finally we discussed how to indicate our intention to use the global level variable using the “global” keyword.
In this post we’ll look at a technique to return multiple values from the same function.
Tuples
I have to confess that the title and the topic of this post is misleading. It’s not possible to return multiple values from functions. I’m not aware of a single major programming language which allows this. C# has the “out” keyword for function parameters that approximates this behaviour but it’s not the same as a function that truly returns more than a single value.
In Python we can instead return a collection of return values. The collection type that becomes useful in this context is called a tuple. A tuple is a read-only collection that cannot be modified at all after it’s been constructed. You cannot add new or update and remove existing values.
Consider the following function which performs the 4 basic arithmetic operations on two numbers and returns them:
def calculate(first_number, second_number): sum = first_number + second_number diff = first_number - second_number div = first_number / second_number mult = first_number * second_number return sum, diff, div, mult
The return statement really does look like it will return 4 values. In fact that’s a notation to put all 4 values in an immutable tuple collection. Let’s see what a tuple looks like:
all_results = calculate(8,4) print(all_results)
This prints…
(12, 4, 2.0, 32)
So a tuple is a collection delimited by parenthesis. We saw that dictionaries used {} and lists used [] for construction purposes. Tuples are constructed using parenthesis instead:
tup = (1,4,5,6)
We can access the individual elements in a tuple using indexers:
sum = all_results[0] diff = all_results[1] div = all_results[2] mult = all_results[3]
Read the next post here.
Read all Python-related posts on this blog here.
Thanks for sharing. Very informative article. I learned many unknown things
Andras,
Maybe it’s nomenclature, but I believe you are incorrect in saying Python cannot return multiple values. Your “calculate” function, for example, could be called by this statement:
sum, diff, div, mult = calculate(a,b)
and the results would be returned to the four different variables. Also, although you are correct in that you can’t change the values in a tuple, you could return the multiple values in an array, which you could then modify with standard array statements.
Bill D.
Andras is correct; Python only returns a single value.
That said, in your example “calculate” returns a single tuple but it is the assignment statement that “unpacks” the tuple into the four variables.