Luis Santos
Luis Santos

Reputation: 33

How to make the "number of returns" a variable

Lets consider a normal function:

def function(stuff):
    return result

To call it and get the result in a variable:

variable = function(stuff)

I can do the same with 3 (for example) results:

def function(stuff):
    return result1, result2, result3

To call it and get the results in 3 variables:

variable1, variable2, variable3 = function(stuff)

My question is: How can I write a function that automatically reads and changes when I set a variable called "number of results". Or, in my real case, the "number of results" will depend on the length of my variable stuff (the variable stuff is a list of arrays).

I hope this question was not answered before.

Upvotes: 3

Views: 91

Answers (2)

Jacob Krall
Jacob Krall

Reputation: 28825

You can create a list with the number of elements you want, then return tuple(yourList).

However, you could then just return the list directly. Python idiomatically doesn't care much about the return types of stuff, so any caller that is looking for an iterable like tuple can iterate over the list just as well.

A list can be unpacked, as well:

>>> foo(3)
[1, 2, 3]
>>> a, b, c = foo(3)
>>> a
1
>>> b
2
>>> c
3

Upvotes: 4

martineau
martineau

Reputation: 123473

Just construct and return a container of results (such as a tuple or list):

For example:

import random

def function(stuff):
    number_of_results = random.randrange(1, 4)
    results = tuple(random.randint(0, 100) for _ in range(number_of_results))
    return results

for _ in range(5):
    print(function(None))

Sample output:

(0, 28)
(66,)
(62, 63, 88)
(99, 89, 67)
(87, 91)

If you want to assign the values returned to separate variables, you can, but knowing how many the function will return will be necessary. For example, if you somehow knew in advance it was going to return three things, you could write: variable1, variable2, variable3 = function(stuff). For that reason it would probably be better to just expect it to return a container and process its contents following the call to the function.

Upvotes: 2

Related Questions