Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get multiple output variables into a list?

I’m wondering if there’s a way of getting multiple outputs from a function into a list. I’m not interested in creating a list inside of a function for reasons I’m not going to waste your time going into.

I know how many output variables I am expecting, but only through using the annotations["return"] expression (or whatever you call that, sorry for the noobish terminology) and this changes from case to case, which is why I need this to be dynamic.

I know I can use lists as multiple variables using function(*myList), but I’m interested in if there’s a way of doing the equivalent when receiving return values from a function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Cheers!

Pseudocode:

function():
   x = 1
   y = 2
   return x, y

variables = function()
print(variables[0], " and ", variables[1]

result should be = "1 and 2"

>Solution :

yes, with the unpacking assignments expression ex a,b,c= myfunction(...), you can put * in one of those to make it take a variable number of arguments

>>> a,b,c=range(3) #if you know that the thing contains exactly 3 elements you can do this
>>> a,b,c
(0, 1, 2)
>>> a,b,*c=range(10) #for when you know that there at least 2 or more the first 2 will be in a and b, and whatever else in c which will be a list
>>> a,b,c
(0, 1, [2, 3, 4, 5, 6, 7, 8, 9])
>>> a,*b,c=range(10)
>>> a,b,c
(0, [1, 2, 3, 4, 5, 6, 7, 8], 9)
>>> *a,b,c=range(10)
>>> a,b,c
([0, 1, 2, 3, 4, 5, 6, 7], 8, 9)
>>> 

additionally you can return from a function whatever you want, a list, a tuple, a dict, etc, but only one thing

>>> def fun():
        return 1,"boo",[1,2,3],{1:10,3:23}

>>> fun()
(1, 'boo', [1, 2, 3], {1: 10, 3: 23})
>>> 

in this example it return a tuple with all that stuff because , is the tuple constructor, so it make a tuple first (your one thing) and return it

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading