1

I want to get the name of the variable in a list with the index. For example:

a = 1  
b = 2
list = [a, b]
print(list[0])

and the output is 1
Is there a way to get "a" as a String instead of 1?

Also, the above code is just an example. I am coding in pygame, so the actual type of values of the variables in the list is Surface, not int.

Thank you for helping

Ching Chang
  • 141
  • 6
  • 11
  • 2
    How would you use this exactly? It seems this is likely to be an XY problem you're trying to address here... – Jon Clements Aug 27 '18 at 11:55
  • 1
    Your list doesn't contain *variables*, it contains *values*. Those values happen to come from variables in this case, but that's completely irrelevant - the values know nothing about any names that have been used to refer to them. – jasonharper Aug 27 '18 at 11:55
  • 1
    Short answer: no – Mia Aug 27 '18 at 11:57
  • Just use `dict`: `{'a': 1, 'b': 2}`. With Python 3.7+ you can assume dictionaries are ordered. – jpp Aug 27 '18 at 12:00
  • to declare a variable named `list` is wrong – Flint Aug 27 '18 at 12:10
  • OK I understand it now. I will change it to a dictionary instead. Thank you all for answering. – Ching Chang Aug 27 '18 at 15:23

1 Answers1

0
a = 1  
b = 2
list = [a, b]
a_name = [k for k,v in globals().items() if id(v) == id(list[0])][0]
print(a_name)
floydya
  • 353
  • 4
  • 12
  • 4
    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Narendra Jadhav Aug 27 '18 at 12:07