Python Functions: Returning Multiple Values

Python Functions: Returning Multiple Values

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

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Difference Between Function and Method in Python
  3. Default Arguments in Python
  4. Passing Object of The Class as Parameter in Python
  5. pass Statement in Python

You may also like-

  1. Multiple Inheritance in Python
  2. List in Python With Examples
  3. Python count() method - Counting Substrings
  4. Python Program to Find Factorial of a Number
  5. static Import in Java With Examples
  6. Doubly Linked List Implementation Java Program
  7. How to Create Immutable Class in Java
  8. How to Install Node.js and NPM in Windows
Find Out
Related Post

Ikuti AltairGate.com pada Aplikasi GOOGLE NEWS : FOLLOW (Dapatkan Berita Terupdate tentang Dunia Pendidikan dan Hiburan). Klik tanda  (bintang) pada aplikasi GOOGLE NEWS.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad