2

How might one call a function which returns two variables?

For example:

def F1(x):
    do something with x
    return y, z

def F2(y, z, q):
    do lots of other things
    return profit

What syntax should be used to call F1 from F2 which makes in clear which output from F1 is y and which is z.

My intuition says

F2(F1(x), q) 

Which is fine, but then how to call y and z within F2?

3
  • why not just do y,z = f1(x) p =f2(y,z,q) Commented Nov 3, 2015 at 15:24
  • Hi @Florin Ghita. Do you mean, for example, that I use the variable name returned in F1 to reference the value in F2? Commented Nov 3, 2015 at 15:25
  • @Busterdust, thanks! So outside F2 I would use y,z = F1(x) and then call these variables in F2? Is there a way to do this without the intermediate step? Commented Nov 3, 2015 at 15:27

6 Answers 6

3

You can change the F2 function definition to following:

def F2((y, z), q):

and call it as:

F2(F1(x), q)

The 0th element of the returned tuple from F1 will be taken as y from F2 and 1st element of the returned tuple will be taken as z from F2.

Sign up to request clarification or add additional context in comments.

Comments

1

You are close to solution. Your F1 return 2 values, but if you put directly on F2 parameters, F2 will see in input

(y,z) <--- tuple
q <--- variable

A solution is to store the return of F1 into 2 variables then passing them to F2

y,z = F1(x)
F2(y,z,q)

Another solution is the use of *args First pass q, then y and z

def F2(q, *args):
    y, z = *args
    some other code

def F1(x):
    some code
    return y, z

F2(q, *F1(x))

1 Comment

Thank you. This was a very clear and informative answer.
0

You can use *args to pass multiple positional arguments to your function :

Demo:

>>> def F(q,*args):
...    x,y=args
...    print x,y
...    print q
... 
>>> F('q',4,5)
4 5
q

And when a function returns multiple arguments, you can use * to unpack the tuple at call time, to pass all the arguments to function:

>>> def A():
...    return 5,6
... 
>>> F('q',*A())
5 6
q

Comments

0

You can return into a tuple:

a, b = F1(x)

Comments

0

Not very elegant, but you can call F2 as:

F2(F1(x)[0], F1(x)[1], q)

This will return profit

Comments

0

If you want to call F2 like that, you would use:

F2(*F1(x), q=q)

This unpacks the results of F1, and only named arguments can follow that kind of operation, so you have to call q by it's name. But it probably makes more sense to unpack the results of F1 first.

y, z = F1(x)
F2(y, z, q)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.