Pepe Pepe - 1 month ago 9
Python Question

Is it possible to automate variable creation in a for loop in python?

I was wondering if there is a nice way to use a loop in order to create and assign variables. I usually catch the objects in a list, but it would be nice to access each by a variable name.
For example I want to automatically create several machine learning models with different parameters and assign each model to variable model_1,model_2 and so on.
something that could look like this:

for i,parameter in enum(list_of_parameters):
model_ + i = model_generator_function(parameter)


Thanks for your help!

Answer

Thing is, you cannot generate the name of the variables at runtime, so you must hold them somewhere. I suggest using a dictionary.
Try to do something like this:

models = dict()

for parameter in list_of_parameters :
    for i in range(len(list_of_parameters)) :
        models["model_" + str(i)] = model_generator_function(parameter)

You can access your variables easily (models[model_name]).