0

Is there a simple way of getting the name(not contents) of every list item and converting it to string?


text0= " zero zero zero zero..."
text1= " one one one.... "
text2= " two two two...."
text3= " three three...."


text_grouped=[text0, text1, text2, text3]

for i in text_grouped:
    print(i)

the above prints the contents of variables but not the actual names.

I would like the result to be: text0, text1, text2, text3

Flanimal
  • 56
  • 6
  • 1
    not unless you have a `namedtuple` or a `dictionary` to map names with the values. – Krishna Chaurasia Jan 23 '21 at 13:18
  • Why are you storing it this way anyway? Seems like you'd be better off with a dictionary. Why do you need the variable names? This is highly suggestive you need a dict, rather than some hacky way to retrieve "variable names". – costaparas Jan 23 '21 at 13:18
  • Check https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string – Jongsu Liam Kim Jan 23 '21 at 13:20
  • If you have a specific pattern in the name of the list then you can find them from `dir()` – Epsi95 Jan 23 '21 at 13:25

1 Answers1

0

You can use the varname library (its not part of the standard python library, so you have to install it). Sample code:

from varname import nameof

some_var1 = "somevar1"
some_var2 = "somevar2"
lst = [somevar1, somevar2]
print(nameof(lst[0]), nameof(lst[1]))
TheEagle
  • 5,808
  • 3
  • 11
  • 39