In Python a function can return multiple values, that is one of the difference you will find in a Python function and function (or method) in a language like C or Java.
Returning multiple values in Python
If you want to return multiple values from a function you can use return statement along with comma separated values. For example-
return x, y, z
When multiple values are returned like this, function in Python returns them as a tuple. When assigning these returned values to a variable you can assign them to variables in sequential order or in a tuple. Let’s try to clarify it with examples.
Python function returning multiple values example
In the example there is a function that adds and multiplies the passed numbers and returns the two results.
def return_mul(a, b): add = a + b mul = a * b # returning two values return add, mul # calling function a, m = return_mul(5, 6) print('Sum is', a) print('Product is', m)
Output
Sum is 11 Product is 30
As you can see in the function two values are returned which are assigned to two variables in sequential order
a, m = return_mul(5, 6)
value of add to a and value of mul to m.
You can also assign the returned values into a tuple.
def return_mul(a, b): add = a + b mul = a * b # returning two values return add, mul # calling function t = return_mul(5, 6) # getting values from tuple print('Sum is', t[0]) print('Product is', t[1])
Output
Sum is 11 Product is 30
That's all for this topic Python Functions: Returning Multiple Values. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-