-1

I have two lists in python

targetvariables = ['a','b','c']
featurevariables = ['d','e','f']

I would like to create three lists such as the following:

a_model =  ['a','d','e','f']
b_model = ['b','d','e','f']
c_model = ['c','d','e','f']

I have about 15 target variables and 100+ feature variables so is there a way to do this in a loop of some kind? I tried but I couldnt work out how to assign a list name from a changing variable:

for idx,target in enumerate(targetvariables):
    target +'_model' = targetvariables[idx] + featurevariables

SyntaxError: can't assign to operator

The end goal is to test machine learning models and to make things easier I would like to simply call:

df[[a_model]] 

to then use in the ML process.

SOK
  • 1,732
  • 2
  • 15
  • 33
  • 1
    One can use a dictionary for this. The key is like the variable name, and the value would be the list. – jkr Apr 10 '21 at 12:49
  • any idea how to do this and then how to reference `df[[a_model]]` in that regard? thanks – SOK Apr 10 '21 at 12:51

1 Answers1

2

Short answer: DO NOT DO THIS!

By doing this you're corrupting the global namespace and that's not recommended. If you really need to do this, this is how:

for target_var in targetvariables:
    # access the global namespace and modify it
    globals()[f'{target_var}_model'] = [target_var] + featurevariables

Alternative #1

Instead of storing the lists in variables, store them in a container, for example, a dict:

models = {}  # create an empty dict
for target_var in targetvariables:
    # the same as the last example but with 'models' instead of 'globals()'
    models[f'{target_var}_model'] = [target_var] + featurevariables

Then access the lists like so:

>>> models['a_model']
['a','d','e','f']

You can also easly change the code so that the keys of the dict would be the variable name itself, without "_model".

Alternative #2

Instead of storing the lists, create them on the fly with a function:

def get_model(target_var):
    return [target_var] + featurevariables

Then access the lists like so:

>>> get_model('a')
['a','d','e','f']
Roy Cohen
  • 1,540
  • 1
  • 5
  • 22
  • Please refrain from answering questions that are asked literally every day. It makes the site more difficult to navigate. – TigerhawkT3 Apr 10 '21 at 13:02
  • 1
    So, seriously Use Alternative 1. Having that said you could do this within a functions scope with locals() instead of globals(), but seriously; just enjoy this as a piece of trivia and never use it. – Rory Browne Apr 10 '21 at 13:06
  • ah this is great - thanks @Roy! – SOK Apr 10 '21 at 13:09