Python function return multiple values [SOLVED]

Introduction

A function in Python is a collection of connected statements that carry out a certain activity. Functions assist in segmenting our script into manageable, modular portions. Our program becomes more structured and controlled as it becomes bigger and bigger. It also makes the code reusable and prevents repetition. Functions help us to reduce the duplication of code and decompose big and complex problems into smaller and simplest forms. Using functions in your daily programming will help you to produce clean code.

Python function return multiple values [SOLVED]

There are two types of functions in Python. Some functions are pre-defined which comes along with Python installation. The other type of functions are called user-defined functions, these are those functions that are designed by us for our custom purposes. We are not discussing built-in functions in this training. This article aims to familiarize you with python functions that return multiple values.

Advertisement

 

Types of functions in python

Before going to jump in detail, let’s first understand the different types of user-defined functions in python. A function can be of any nature, some functions do not accept any value as a parameter and some do. Some functions accept values and also return some values. Let’s discuss them one by one first.

 

Void() function in python:

In simple words, a void function is a function that does not accept any value as a parameter and does not return any value. These types of functions are also called non-fruitful functions. Let’s take an example to understand them well.

# Example of void() function
def website_I_love():
    print('GoLinuxCloud')
# let's call the function above
website_I_love()

In python, a function is defined with a statement def, after that, we give a name to our function. In the above code snippet, we are defining a void function that does not take any value as a parameter and does not return any value. The above function will print GoLinuxCloud whenever we call it.

Output:

GoLinuxCloud

 

Return functions in python:

In python, a return function is a function that returns some values when we call it. These types of functions can also accept values and then perform some operations on the values and return the results. Function syntax is flexible enough to support multiple arguments and multiple return values.

 

Return multiple values from a function in python

In Python, we can also return multiple values from our user-defined functions. These types of functions also use the return statement as we already saw previously. These functions will take some values, process them and return multiple values. Let’s understand this better with an example.

Advertisement
def function_name(arguments):
     indented_statements

In this syntax, arguments is a list of argument names, separated by commas if there’s more than one. Here’s the syntax of the return statement:

return value

You can also return multiple values:

return value, value ...

Finally, you can omit the return value. If you do, the effect is the same as the statement return None.

return # Same effect as return None

Execution of a return statement causes immediate exit and return to the caller of the function. Reaching the end of a function causes an implicit return—returning None by default. (Therefore, using return at all is optional.)

 

Example 1: Return values in a tuple

def Detailed_Mark_Sheet():
    maths = 98
    english = 80
    physics = 90
    chemistry = 70
    total = maths + english + physics + chemistry
    avg = (maths + english + physics + chemistry)/4
 
    return (maths, english, physics, chemistry, total,avg)
 
maths, english, physics, chemistry, total, average = Detailed_Mark_Sheet()
print('Maths: ',maths)
print('English: ',english)
print('Physics: ',physics)
print('Chemistry: ',chemistry)
print('Total: ',total)
print('Average: ',average)

The beauty of python is that it has Tuples. The multiple values from a function are returned using a tuple. A tuple is a comma-separated list that will hold the values coming from a function. In the above code snippet, we have defined a function called Detailed_Mark_Sheet(), this function has the marks of a student with total and average. We have defined a tuple in a sequence, the function will take the first value which is Maths, and give it to the tuple's first element and second to the second element, and so on. Finally, all the values which are defined in the function will be stored in the tuple.

Output:

Advertisement
Maths:  98
English:  80
Physics:  90
Chemistry:  70
Total:  338
Average:  84.5

 

Example 2: Return values in a list

This example is the same as the above, the slight difference is that we are taking two numbers from the user, and those two numbers are passed to the function, and the function will apply addition, subtraction, multiplication, and division. The values will be stored in a list this time and the function will return a list. Have a look at the code below.

def calculator(val1, val2):
    add = val1 + val2
    multiply = val1 * val2
    divide = val1 / val2
    subtract = val1 - val2
 
    return [add, multiply, divide, subtract]
 
no1 = int(input('Enter a Number: '))
no2 = int(input('Enter a Number: '))
print(calculator(no1, no2))

Output:

Enter a Number: 100
Enter a Number: 50
[150, 5000, 2.0, 50]

 

Example 3: Return multiple values in a dictionary

Here is a simple function to return multiple values in Python.

def f():
    a = 5
    b = 6
    c = 7
    return a, b, c

a, b, c = f()

Here the function is actually just returning one object, a tuple, which is then being unpacked into the result variables. In the preceding example, we could have done this instead:

return_value = f()

In this case, return_value would be a 3-tuple with the three returned variables. A potentially attractive alternative to returning multiple values like before might be to return a dictionary instead:

def f():
    a = 5
    b = 6
    c = 7
    return {"a" : a, "b" : b, "c" : c}

This alternative technique can be useful depending on what you are trying to do.

Advertisement

 

Summary

In this article, we have studied the basics of python functions. We have seen the void functions and returning functions with the help of easy and simple examples. You can have functions return multiple values by putting them in a tuple and having the caller take advantage of Python’s unpacking syntax.

  • Multiple return values from a function can also be unpacked by catch-all starred expressions.
  • Unpacking into four or more variables is error prone and should be avoided; instead, return a small class or namedtuple instance.

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X