How To Return Multiple Values In Python

Returning multiple values from a function can be quite useful in various situations, such as performing mathematical calculations, string manipulations, or returning status information alongside the actual result.

Python provides several ways to return multiple values from a function, including using tuples, lists, dictionaries, and classes/objects. In this tutorial, we will explore these methods and provide examples of how to use them in your own Python code.

Method 1: Returning a Tuple

Tuples are immutable sequences in Python, which can store multiple values. You can return a tuple from a function by simply separating the return values with commas. Here’s an example of a function that calculates the area and perimeter of a rectangle:

Area: 50 Perimeter: 30

Method 2: Returning a List

Lists are mutable sequences in Python. You can return a list from a function just like a tuple but with the returned values enclosed in square brackets []. Here’s the same example as before, but this time returning a list:

Area: 50 Perimeter: 30

Method 3: Returning a Dictionary

Dictionaries store key-value pairs, which can be particularly handy when you want to return multiple values with labels. Here’s our area and perimeter example, this time returning a dictionary:

Area: 50 Perimeter: 30

Method 4: Returning an Object

Sometimes, it might be more suitable to return an object that represents the values you want to return, particularly if they are complex or need to be processed further. Here’s an example using a class to represent a rectangle:

Area: 50 Perimeter: 30

Conclusion

In this tutorial, we have learned about four different ways to return multiple values from a Python function using tuples, lists, dictionaries, and objects. Depending on the requirements of your specific case, you can choose the method that best suits your needs and provides better readability and maintainability to your code.