-3

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
  • 1
  • 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

-2

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
  • 30,962
  • 25
  • 85
  • 135
  • [**Do not ever use `eval` (or `exec`) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer.**](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Karl Knechtel Jul 05 '22 at 00:03
-3

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
  • 308
  • 3
  • 8
  • [**Do not ever use `eval` (or `exec`) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer.**](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – Karl Knechtel Jul 05 '22 at 00:02