10

After a bit of research I found these questions (1, 2) about variables. Similarly, I would like to know if it is possible to get the name of a list as a string in Python, for example:

for a list lst = ['a', 'b', 'c'], a method like get_name_of_list_as_string(lst)

should return 'lst' # String.

Is something like that even possible in Python, and if so, how exactly?

Community
  • 1
  • 1
  • @ShadowRanger Good thing I included that link you mention as duplicated from in my original description of this question! :/ –  Jun 13 '16 at 11:21
  • @hask.duk: Then why even ask the question if you already know the answer? There is nothing special about `list` vs. any other variable name. – ShadowRanger Jun 13 '16 at 11:23
  • 2
    @ShadowRanger As you 've said, it is all about knowing. I didn't. Hence my question. –  Jun 13 '16 at 11:25

1 Answers1

10

It's not possible; names hold references to objects, but objects do not hold references to the name(s) (if any) which reference them. It's a one-way flow of information. Remember, not all objects even have names, and many objects have more than one, so even if you did terrible things with stack inspection to try to find the name heuristically, get_name_of_list_as_string([]) is going to fail, as will x = [[]], get_name_of_list_as_string(x[0]).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271