This post will discuss how to return multiple values from a function in Python.

1. Using Tuples

The preferred approach to return just two or three fields from a function in Python is using a Tuple. A tuple is a ordered and immutable collection of items, which are created by separating the values with commas and enclosing them within the parentheses. The idea is to pack values to be returned in a tuple, return the tuple from the function and unpack it inside the caller function. The following example shows how we can use tuples to return two fields of different types from a function.

Download  Run Code

 
We can use tuples when the total values to be returned is less. The more the values, the more difficult it is to manage and correctly unpack them.

2. Using Named Tuples

To handle the problems associated with a tuple, we can use named tuples. A named tuple are tuple-like objects but have fields accessible by attribute lookup. We can create a named tuple by using the collections.namedtuple() built-in function in the collections module. Then, we can use indexing or dot notation to access each value in the named tuple by its position or name, respectively. The following code example shows how to implement named tuples:

Download  Run Code

3. Using Dictionary

Instead of using a tuple or a named-tuple, we can also use a dictionary to return multiple values from a function in Python. This can be done by assigning each value to a key and enclosing them within curly braces. This can be used when the total number of values to be returned is more. For example:

Download  Run Code

4. Using Class

The last option to return multiple values from a function is by creating an instance of a class containing all fields and return it. The following code example implements a class used to return three fields of different types from the function foo().

Download  Run Code

That’s all about returning multiple values from a function in Python.