Search code examples
pythonlistvariables

Get variable's name from variable


I am a novice Python programmer and I have recently met a problem I can't find a way to deal with. The thing is, I have one list with elements and one variable with name of this list in form of string. It looks like this (I use python 3.7):

my_list = ['a', 'b', 'c', 'd']
var1 = 'my_list'

And my objective is to iterate through this list using for loop without using name of this list in command, only the variable's value (which is list's name). I tried to simply use var1 as the list itself, but, of course, it did not work out:

my_list = ['a', 'b', 'c', 'd']
var1 = 'my_list'

for item in var1:
    print(item)

Is there a way to sort this out somehow?


Solution

  • You are assigning a string value to the new variable, which will always return plain text that says my_list, you need to remove the apostrophes around it. It should look like this:-

    var1 = my_list
    

    If you want to keep it a string you could use a method called eval

    it would look like this:-

    for i in eval(var1):