pythonlist

How to print variable name in a list


I just want to print the variable's name as in the case below:

Andi = 100
Bill = 50
Kira = 90
list1 = [Andi, Bill, Kira]
for i in list1:
    print(i)

How can I have the variable name and value printed together?

This solution was shown in a now deleted answer, and there was a comment saying using eval is bad practice:

Andi = 100
Bill = 50
Kira = 90
list1 = ['Andi', 'Bill', 'Kira']
for i in list1:
    print(i, eval(i))

Is there a better way?


Solution

  • You can't do this with plain variables. Use a dictionary instead:

    mydict = {
        'Andi': 100,
        'Bill': 50,
        'Kira': 25
    }
    
    for name in mydict:
        print(name, mydict[name])