chevron_left
660 points
6 2 1

How many values can a function return.
Photo by Mati Mango

`Python` functions can return multiple values. These values can be stored in variables directly. A function is not restricted to returning a variable, it can return zero, one, two, or more values. This is the default property of `python` to return multiple values/variables which is not available in many other programming languages like C++ or Java. In this article, we will dive into exploring different ways of a `function` returning a `value`.

How many values can a function return? #

You can return multiple values by bundling those values into a dictionary, tuple, or a list. These data types let you store multiple similar values. You can extract individual values from them in your main program. Or, you can pass multiple values and separate them with commas. Python functions can return multiple values. To return multiple values, you can return either a dictionary, a Python tuple, or a list to your main program. This guide discusses how to return multiple values to the main program using these two methods. Let’s begin.

You can return multiple values from a Python function using a list that contains multiple values. A tuple with multiple values. A dictionary with multiple records and multiple values separated by commas.

Objectives that will help to solve this problem. #

This guide explains Python: Returning multiple values from a function. Functions are used to perform specific tasks that are most likely to return a specific value. However, depending on your use case, you may need to return more than one value. The code to do this in other programming languages can be quite complex, but Python provides some convenient methods for returning multiple values. Most of these methods return these values using collection data types. We'll take a closer look at all of them below.

It all depends on your preferences and preferred methods. Choosing the dictionary root requires less setup work. Alternatively, you can choose the class root as it helps avoid confusion about what the dictionary stands for. Alternatively, you can select a generator and specify the values one by one.

To return multiple values from a function, you can return a tuple, list, or dictionary object, depending on your requirements.

def func(x):
y0 = x+ 1
y1 = x * 3
y2 = y0 ** 3
return (y0, y1, y2)

However, above program get problematic as the number of values returned increases.

In case we want to return six or seven values? Sure, we can keep tupling them, but it gets easy to forget which value is where. Also, it gets a little messy to unpack them wherever we want to receive them.

The Solution #

You can return multiple values by separating the values to return with commas. These values must appear after the Python return statement. Write a program to calculate the number of sales in an electronic store. Only count sales over $500. Our program also calculates the average value of each sale. First, let's define a Python array containing the list of sales.

sales = [59.99, 240.00, 655.25, 75.99]

Next, create a Python function that calculates the average number of sales and purchases over $500.

def calculate_data(sales):
    over_limit = 0
    for s in sales:
         if s > 500:
             over_limit += 1

    average_purchase = sum(sales) / len(sales)
    return over_limit, average_purchase

This function iterates through each sale in the list in a loop. If the sale exceeds $500, the "over_limit" Python variable is incremented by 1. Then, calculate the average purchase value by dividing the total value of all sales by the number of sales.

At the end of the function, use the return statement to return the "over_limit" and "average_purchase" values to the main program. It just calls the function and prints the data calculated by the program to the console.

over_limit, average_purchase = calculate_data(sales)
print("{} sales were made over $500. 
The average purchase was ${}.".format(over_limit, round(average_purchase)))

Solution one

Both lists and tuples can store multiple values. This means they can be used to return multiple values to the main program. If the returned values are related in some way, it's best to use a list or tuple. However, you can return a collection of values using this approach. Returns the average purchase size and the number of purchases over $500 to the main program. To do this, let's go back to our previous example and modify it slightly to use a list.

def calculate_data(sales):
over_limit = 0
for s in sales:
if s > 500:
over_limit += 1
average_purchase = sum(sales) / len(sales)
return [over_limit, average_purchase]

Just split the values into a single list. Our list includes the number of purchases over $500 or the average purchase amount.

It can also return a tuple data structure. To do this, replace the square brackets with curly braces. A big factor to consider is that tuples cannot contain duplicate values. Avoid using tuples if the two values you pass to the main program can be the same. To access these values in the main program, you must use an index.

values = calculate_data(sales)
print("{} sales were made over $500. 
The average purchase was ${}.".format(values[0], round(values[1])))

Solution two

As you work with more values, it might be easier to return a dictionary that associates a label with each value. Modify the last function to use a dictionary to return multiple values to the main program.<'/span>

def calculate_data(sales):
    over_limit = 0
    for s in sales:
         if s > 500:
             over_limit += 1
    average_purchase = sum(sales) / len(sales)
    return { "limit": over_limit, "average": average_purchase }

This function returns a dictionary with two keys and values. Each value can be uniquely identified by the keys 'limit' and 'mean'. You will need to modify your function calls and print statements to support this new syntax.

values = calculate_data(sales)
print("{} sales were made over $500. 
The average purchase was ${}.".format(values["limit"], round(values["average"])))

The Conclusion

You can return multiple values from a function using either a dictionary, tuple, or list. These data types allow you to store multiple values. There is no special syntax for returning multiple values, but these methods are a good alternative. For small sets of values, the comma-separated method is cleaner and easier to understand. Suppose you want to return a wider range of values from your function. You can use dictionaries to send multiple values back to the main program.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

How can a call to an overloaded function be ambiguous? zhteja - Aug 10
Given an array of ints, return true if the array contains a 2 next to a 2 somewhere. NoirHusky - Sep 8
How to check a item is present in list Saikat Saha - Sep 14
List indices must be integers or slices, not tuple zhteja - Jul 30
How are python dictionaries different from python lists? Ferdy - Jul 23
Order a list of numbers without built-in sort, min, max functions in Python Ferdy - Aug 4
Add to the list in a loop using python amr12345a - Jun 2
The function evaluation requires all threads to run zhteja - Jul 28
TypeError: unsupported operand type(s) for -: 'list' and 'list' Ferdy - Sep 9
Linked list in python Baribor Saturday - Jul 30
Print the contents of file in reverse order in Python Ferdy - Jul 28
Python read file line by line into array Ferdy - Jul 19
Divide every element in list python Baribor Saturday - Jul 16
Invalid subscript type 'list' r Samshow-cyber - Jun 1
Given a string, return a string where for every char in the original, there are two chars. Ankur Ranpariya - Jul 19
Check if a number is between two values using python amr12345a - Jun 1
A function inside another function in python Ankur Ranpariya - Jul 20
How to check if a key exists in a Python dictionary Ferdy - Aug 30
How to Reverse a given string in python Ankur Ranpariya - Jul 21
How to Read a File line by line in Python umasivasu21 - Aug 2