1

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!

Picard
  • 983
  • 9
  • 23
  • 2
    Variable variable names are a bad idea. A really bad idea. Put your data in a `list` or in a `dict`. – Matthias Nov 02 '16 at 08:16
  • Thanks, that's what I thought. Found it also here [link](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-via-a-while-loop) – Picard Nov 02 '16 at 08:20

3 Answers3

5

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 = {}

for parameter in list_of_parameters :
    for i in range(len(list_of_parameters)) :
        models[f"model_{i}"] = model_generator_function(parameter)

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

Right leg
  • 16,080
  • 7
  • 48
  • 81
0

You can use a dictionary where you can create keys dynamically. Try to do something like the following:

data = {}

for i, param in enum(list_of_params):
        data['model_{}'.format(i)] = model_generator_function(param)
ettanany
  • 19,038
  • 9
  • 47
  • 63
0

A dict may be useful, creating keys like "model_0", "model_1" etc. is somewhat awkward tough. If you actually just have a list of models, you can just as well put them in a list:

models = list()
for parameter in list_of_parameters :
    models.append(model_generator_function(parameter))

Or shorter:

models = [model_generator_function(p)
          for p in list_of_parameters]
sebastian
  • 9,526
  • 26
  • 54
  • Thanks, that's what I've done so far. But for me a dict might be the better solution, since it is a lot easier to keep track of the models, e.g. what parameters were used. – Picard Nov 02 '16 at 08:41