The correct way to return more results from functions

Think about a function that computes A and B from C. A is half of C and B is twice C.

it could be like this:

def compute_A_and_B(C):
     A = C/2
     B = C*2
     #how do I return A and B when I call this function?
     return A, B #this way?

#fox example?
A, B = compute_A_and_B(C)

actually I assign results A and B to a list in the function, I return the list, and then I get the results from the list outside the function, but this seems to be an inefficient way.
Do you have some better solutions? Thankyou!

hi,

i found this example on http://www.wellho.net/mouth/1202_Returning-multiple-values-from-a-function-Perl-PHP-Python-.html


# Returning a tuple from a function
def doingit(v):
  a = v+10
  b= v*20
  c = 56/v
  return c,a,b; # returns a tuple
# function call will return a tuple (into z)
z = doingit(7)
# This syntax splits the tuple out into a
# series of individual variables (w, l and k)
w,l,k = doingit(7)
# Show that it has worked as expected
print w, l, k
print z

Thank you very much! Where did you find it? :slight_smile:
So I was very near!

i don’t see any problems with this

of course, you could do like:

A_B_list = compute_A_and_B(C)
A_B_list
>>> [a, b]

or return a list / dict:

return [A, B]
return {"a": A, "b": B}

or if compute_A_and_B was a class something like

class compute_A_and_B:
    def __init__(self, C):
        self.a = C // 2
        self.b = C * 2

AB_ob = compute_A_and_B(C)
AB_ob.a, AB_ob.b

or AB_ob.dict for
{“a”: A, “b”: B}

The snippets of Lell and Olifant are equivalent. The function returns a tuple (not a list!) and the tuple is then unpacked.
This is the standard way in Python, and quite efficient.

The last two snippets of CoDEManX, using dict or class objects, is a bit less efficient (but only a little bit); but if you are returning 10 variables or so, this is much more readable.