List variable name involves different variable outputs

Hi, i have a couple of lists to be appended to a particular list dynamically:
The desied result should be categorized=[[‘Neutral’,‘elderly’],[‘Short’,‘woman’],[‘tall’,‘man’]]
i just wonder if variable outputs can be a part of anthor variable name?
The code created so far is shown below:
Thank you very much.

`categorized=[]
list0=['tall','man']
list1=['Short','woman']
list2=['Neutral','elderly']
controll=2
while controll>=0:
    print('cont',list+f'{controll}')         
    categorized.append(list+f'{controll})
    controll-=1
print(categorized)
print('cont',list+f'{controll}')`

Why do you need to do this dynamically? That is to say, why do you define list0 et al. in the first place, instead of

categorized = [
    ['Neutral','elderly'],
    ['Short','woman'],
    ['tall','man'],
]

or

categorized = []

# Time passes...

new_lists = [
    ['Neutral','elderly'],
    ['Short','woman'],
    ['tall','man'],
]

for x in new_lists:
    categorized.append(x)

You may find these SO questions helpful:

Basically, you’re trying to concatenate a string (“list”) with an int (controll), resulting in list2, list1, list0 and then use those resulting concatenated strings as variables to append to another list, but you’re using the class list instead of just a string that says “list”.

I think you might mean f'list{controll}' or 'list' + f'{controll}' or just "list" + str(controll) (with list in quotation marks)

then to append to the list, you’d use eval()
categorized.append(eval(f'list{controll}'))

If you were to put list in quotes here, it still would only append “list2” or “list1” to the list not actually [‘Neutral’,‘elderly’] or [‘Short’,‘woman’], using eval() is what allows it to be recognized as a variable instead of just a string.

Thank you for your help.I have solved the question.

1 Like