-2

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?

Kozix125
  • 3
  • 2
  • 1
    You want the opposite of your question : get variable from variable's name – azro May 22 '20 at 09:43
  • 1
    That can be done, but it should not be done. There is no good reason to have the name of a local variable in a string. You should organize your code differently. – zvone May 22 '20 at 09:44

2 Answers2

-1

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):
Dharman
  • 26,923
  • 21
  • 73
  • 125
-2

You can use the eval function for this:

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

for item in eval(var1):
    print(item)

The eval function evaluates the given arguments as Python code.

EDIT: I was too slow, when I started the question had not been answered yet, my bad..

Rick
  • 187
  • 2
  • 8