-1

I'm working with python and I was just wondering that is it possible to have variable names be stored in another list.

Achievement = ['hi', 'hey', 'hello']
lines = ['Achievement', 'hi']
print lines[0][2]

I want the output to be 'hello' in this case. Can anyone suggest me any way to achieve that.

glglgl
  • 89,107
  • 13
  • 149
  • 217
Sumit Paliwal
  • 385
  • 1
  • 3
  • 14

4 Answers4

6

Usually if you want to dynamically lookup names in Python code, correct solution is to use mapping. In Python basic mapping object is dictionary. Sample code which does what you want may be following:

d = {'Achievement': ['hi', 'hey', 'hello']}
key = 'Achievement'
index = 2
print d[key][index]
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
1

It would be possible, yes. You can do so by accessing globals() and/or locals() and using their result (which is a dict of varname: varcontent).

But that's very bad style as you can read here.

There are much better ways of doing so, including

Achievement = ['hi', 'hey', 'hello']
lines = [Achievement, 'hi']
print lines[0][2]

or using a dict or other things.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

But if you really wanted to do this

code:

 d=globals()
 d[lines[0]][2]

output:

 'hello'
The6thSense
  • 8,103
  • 8
  • 31
  • 65
1
Achievement = ['hi', 'hey', 'hello']
lines = ['Achievement', 'hi']
print eval(lines[0])[2]
yrykde
  • 11
  • 3