3

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

Coco Liliace
  • 311
  • 5
  • 14

1 Answers1

-1
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
  • 416
  • 6
  • 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
  • It works! Let a, b, c are variables ```lst = [a, b, c]; for x in lst: print([k for k,v in globals().items() if id(v) == id(x)][0])``` – ibilgen Feb 21 '23 at 12:33