How to make the number of return values ​​to a variable

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 results (for example):

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

      

To call it and get the results in three variables:

variable1, variable2, variable3 = function(stuff)

      

My question is, how can I write a function that reads and changes automatically 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 (the variable is a list of arrays).

Hopefully this question hasn't been answered before.

+3


source to share


2 answers


You can create list

with as many items as you want, then return tuple(yourList)

.

However, you can simply return immediately list

. Python idiomatically doesn't care about the return types of things, so any caller looking for an iterable like tuple

can iterate over as well list

.



A list

can also be unpacked:

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

      

+4


source


Just create and return a results container (like 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))

      



Output example:

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

      

If you want to assign return

ed values to separate variables, you can, but know how many functions will be returned. For example, if you somehow knew in advance he was going to return three things you could write: variable1, variable2, variable3 = function(stuff)

. For this reason, it would probably be better to just expect it to return the container and process its contents after the function call.

+2


source







All Articles