Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function within a function unknown number of times

How do I use the output of one function as the argument of another. There is an unknown (X) number of functions and each function is different. The argument to the first function is known (lets call it n).

I have tried to create a list of the functions and use the results of one for another, I can't really get anywhere.

list = [function1, function2, function3, function4, function5.....functionX]

def nestedfunction(list, n):
    a_1 = list[0](n)
    a_2 = list[1](a_1)
    a_3 = list[2](a_2)
    a_4 = list[3](a_3)
    a_5 = list[4](a_4)
    ......
    a_x = list [len(list)-1](a_x-1)
    print (a_x)

Thank you for your help.

like image 206
Python_newbie Avatar asked Dec 10 '25 04:12

Python_newbie


2 Answers

It's way easier than you made it:

funcs = [function1, function2, function3, function4, function5.....functionX]

def nestedfunction(funcs, n):
    for f in funcs:
        n = f(n)
    return n
like image 110
Tim Roberts Avatar answered Dec 11 '25 16:12

Tim Roberts


Iterate over the list and overwrite n with each iteration, then return it:

def nestedfunction(function_list, n):
    for function in function_list:
        n = function(n)
    return n
like image 31
jfaccioni Avatar answered Dec 11 '25 18:12

jfaccioni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!