Return Multiple Values in Python : 2 Steps Only

As a data science programmer, it’s better to return multiple values from a single python function. It makes efficient, flexible, and readable code in python. In this tutorial, you will know how to return multiple values in python through steps.

Steps to Return Multiple Values in Python

In this section you will know all the steps you will follow for the implementation of the example. Let’s start.

Step 1: Define the function

The first step is to define the function that will return the multiple values. Inside the function, there will be three variables that will be returned when the function will be invoked.

Use the below lines of code to define the function.

def multiple_values():
    a = 10
    b = 20
    c = 30
    return a, b, c

Here you can see I have defined three variables a,b, and c that accept an integer value. All these values will be returned using the return a,b, and c statements.

Step 2: Invoke or call the function

After defining the function, now it’s time to call the function. As there are three values returning, therefore you will use the three variables to accept all three variables.

Execute the below line of code to get the values.

x,y,z  = multiple_values()

Below is the full code.

def multiple_values():
    a = 10
    b = 20
    c = 30
    return a, b, c
    
x,y,z  = multiple_values()
print(x)
print(y)
print(z)

Output

returning multiple values from a single function

Here the return values will be returned like a tuple that is (x,y,z) = (10,20,30).

If you want to convert the tuple to a list then use the list() function to typecase the results into the list. To do use the following line of code.

tuple_to_list = list(multiple_values())

Conclusion

If you want to calculate multiple results or values at once then it’s better to use a single function. You can also pass the results to another function as input. By implementing the above steps you are able to define a function that returns multiple values.

I hope you have liked this tutorial. If you have any queries or suggestions then you can contact us for more help.