Search code examples
python-3.xlistinitializationcustom-function

How to initilise a list that contains custom functions without python running those functions during initialisation?


Short version:

  • How do you store functions in a list and only have them be executed when they are called using their index position in the list?

Long Version:

So I am writing a program that rolls a user-chosen number of six-sided dice, stores the results in a list and then organizes the results/ data in a dictionary.

After the data is gathered the program gives the user options from 0-2 to choose from and asks the user to type a number corresponding to the option they want.

After this input by the user, a variable, lets say TT, is assigned to it. I want the program to use TT to identify which function to run that is contained within a list called "Executable_options" by using TT as the index posistion of this function within the list.

The problem I am having is that I have to have the list that contains the functions on a line after the functions have been defined and when I initialize the list it goes through and executes all functions within it in order when I don't want it to. I just want them to be in the list for calling at a later date.

I tried to initialise the list without any functions in and then append the functions individually, but every time a function is appened to the list it is also executed.

def results():
def Rolling_thunder():
def roll_again():

The functions contains things, but is unnecessary to show for the question at hand

Executable_options = []
Executable_options.append(results())
Executable_options.append(Rolling_thunder())
Executable_options.append(roll_again)

options = len(Executable_options)

I am relatively new to Python so I am still getting my head around it. I have tried searching for the answer to this on existing posts, but couldn't find anything so I assume I am just using the wrong key words in my search.

Thank you very much for taking the time to read this and for the answers provided.

Edit: Code now works


Solution

  • The () on the end of the function name calls it - i.e. results() is the call to the results method.

    Simply append to the list without the call - i.e:

    Executable_options.append(results)

    You can then call it by doing e.g.:

    Executable_options[0]()