0
x=['a','b','c']
y=['d','e','f']
z=['g','h','i']
string='x' 

#Now I would like to somehow get the list printed or returned by only using the string variable.

  • Consider explaining more – Luke Hamilton Dec 14 '21 at 17:01
  • `print(eval(string))` – not_speshal Dec 14 '21 at 17:03
  • 1
    Use a `dict` with keys `'x'`, `'y'`, and `'z'` in the first place, instead of using three different variables: `d = {'x': ['a', 'b', 'c'], 'y': ['d', 'e', 'f'], 'z': ['g', 'h', 'i']}`. Then you just use `d[string]`. – chepner Dec 14 '21 at 17:03
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – K450 Dec 14 '21 at 17:08

2 Answers2

0

Use globals or locals:

x=['a','b','c']
y=['d','e','f']
z=['g','h','i']
string='x'

print(globals()[string])
['a','b','c']
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
  • Although this is technically exactly what he asked for it is important to point out that this is almost never the right solution to whatever design problem needs to be solved. Please just use a dictionary instead... – Matt Dec 14 '21 at 17:07
0

If you have multiple list and you want to print them based on some key it's best to use a dictionary.

lstDic = {
    "x":['a','b','c'],
    "y":['d','e','f'],
    "y":['g','h','i']
}
string='x'
print(lstDic[string])
carlosdafield
  • 1,479
  • 5
  • 16