Write a Python Program to Return Multiple Values From a Function

In Python, it is possible to return multiple values from a function.

This can be useful in situations where you need to return more than one piece of information from a function, without the need to use global variables or complex data structures.

In this tutorial, we will look at how to return multiple values from a function in Python.


Defining a Function that Returns Multiple Values

To return multiple values from a function in Python, you simply need to return a tuple containing the values you want to return.

Here is an example of a function that returns multiple values:

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

In this function, we define three variables a, b, and c, and then return them as a tuple.

We don’t need to explicitly create a tuple ourselves, as Python will automatically pack the variables into a tuple when we return them.

Using the Function to Access Multiple Values

Once we have defined our function, we can call it and unpack the tuple to access the multiple values that were returned.

Here is an example of how to do this:

result = multiple_values()
print(result[0])
print(result[1])
print(result[2])

In this code, we call the multiple_values function and assign the result to a variable called result.

We can then access the individual values in the tuple using the index operator ([]) and the index number of the value we want to access.

Another way to unpack the tuple is to assign the values to separate variables like this:

a, b, c = multiple_values()
print(a)
print(b)
print(c)

In this code, we use tuple unpacking to assign the values in the tuple to separate variables a, b, and c.

This is a more concise way of accessing the values than using the index operator.


Conclusion

In conclusion, returning multiple values from a function in Python is easy.

You simply need to return a tuple containing the values you want to return, and then unpack the tuple to access the individual values.

This can be useful in situations where you need to return more than one piece of information from a function.