I want to store functions in a list and then later in a program call those functions from that list.
This works for me, however, I don't know if it is correct :
#example functions, my functions would actually get user input etc.
def func1():
return 2
def func2():
return 3
options = [ func1, func2 ]
#call functions
options[0]()
Is this the proper way to store functions in a list and call it ? Or is there a different, better way to do this?
Yes, you can do it. If you want to call all functions in the list with a "one liner" you can do the following:
results = [f() for f in options]
Yes, this is correct, though if your functions are really one-liner in nature, I would suggest you also have a look at lambdas
, so that your entire code can be reduced to:
options = [lambda: 3, lambda: 2]
As already pointed out in comments, you will Of course need to remember the order of the functions in the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With