-2

I got a list

v = ["a", "b", "c"]

and i want to turn into

v = [a, b, c]

to use the entries as variables. I know that eval() and exec() are not recommended. How can i solve that instead?

Mark
  • 90,562
  • 7
  • 108
  • 148
Hansi Schmidt
  • 95
  • 1
  • 11
  • 2
    Why not use variables in the first place? – Austin Dec 13 '18 at 18:39
  • It's not that eval/exec are bad, it's that needing them in your program might indicate poor design choices. – lakshayg Dec 13 '18 at 18:41
  • 2
    it is bad practice to do this. If you want to map `a, b, c` to something else, use a dictionary. That said, see the post by flyingmeatball if you still want to do it – Tarifazo Dec 13 '18 at 18:43

1 Answers1

-1

If it's a global variable you can use

v = [ globals()[i] for i in ['a', 'b', 'c'] ]

For example...

a = 1                       
b = 2
c = 3

v = [ globals()[i] for i in ['a','b','c'] ]

print(v)
>>>[1, 2, 3]

If it's a local variable in the code block for a separate function/class you can use locals instead. Of course, as mentioned in the comments you should avoid this scenario at all costs in the first place.

KuboMD
  • 684
  • 5
  • 16
  • You should test before post the result. 1. there is an error on your code. This is what you expected to do `[globals()[i] for i in ['q', 'w', 'e']]`. 2. Anyway, this approach raises an exception. – Mauro Baraldi Dec 13 '18 at 18:55
  • Thanks - fixed the code. @MauroBaraldi that's interesting, I don't get one when I try to `print(v)`. What kind of exception? – KuboMD Dec 13 '18 at 19:32
  • Run this code and you will see! – Mauro Baraldi Dec 13 '18 at 19:56
  • I did! My output is just as in my response...when you tried it did you have 'q' 'w' 'e' initialized first? – KuboMD Dec 13 '18 at 19:57