Pmag
Pmag

Reputation: 29

How to run a function with parameters returned by other function?

I have been doing some python project and one question occured in my mind. Here is what I had:

def fun1():
  a = 5
  b = 3
  *some code*
  return a, b

def fun2():
  a, b = fun1() 
  *some code*

fun2()

I was wondering, how or if it is possible in python to do something like this:

def fun1():
  a = 5
  b = 3
  *some code*
  return a, b

fun2(a, b):
 *some code*

fun2(fun1()_1, fun1()_2)

where
fun1()_1 = a
fun1()_2 = b

What I mean here is, is it possible to run a function with appropriate parameters returned by another function and written in parentheses?

Upvotes: 1

Views: 74

Answers (1)

MatsLindh
MatsLindh

Reputation: 52792

You can use argument unpacking. This allows you to programmatically expand lists or tuples as the arguments to functions. You do this by prefixing the value to expand with * (as a side note, you can use **foo to expand a dict named foo as named parameters to a function as well):

>>> def fun1():
...   a = 5
...   b = 3
...   return a, b
...
>>> def fun2(c, d):
...   print(c, d)
...
>>> fun2(*fun1())
(5, 3)

Upvotes: 2

Related Questions