-2

Is there a way i can take variable name inside a list to string?

for example:

abc, def, ghi, jkl = (1,2,3,4)
arr = [abc, def, ghi, jkl]

i need to create a list for every variable name, so i can get:

arr_name = ['abc', 'def', 'ghi', 'jkl']

i need to do this so i don't have to type every variable name for labels in pie plot. Or is creating dict the best way for this problem?

Thanks in advance.

Ahnaf Gibran
  • 58
  • 1
  • 10
  • 2
    Can you expand on why you need to do this? I think there might be other (most natural) solutions if you ask the bigger problem you are trying to resolve here. – Guillaume Aug 09 '20 at 19:44
  • 5
    You don't want to do that, trust me. – Olvin Roght Aug 09 '20 at 19:45
  • 2
    That would be hard to do. The list in `arr` has no memory of where its objects came from. You could potentially scan all of the variables in the namespace and find those that have the same object as the items in the list. That would shorten the list. But if `foo` happened to also be `1`, you wouldn't know whether the first item in the list came from `foo` or `abc`. – tdelaney Aug 09 '20 at 19:47
  • 1
    There are other data structures that may work better. With a `dict`, you could keep a name/value association `{"abc":1, "def":2}`. – tdelaney Aug 09 '20 at 19:49
  • Okay, if you're really want to do that (but you don't, check prev comment), you have to take a look on [`inspect`](https://docs.python.org/3/library/inspect.html) module. – Olvin Roght Aug 09 '20 at 19:49
  • 1
    First, `def` is a reserved word in Python. You cannot have a variable named `def` – GAEfan Aug 09 '20 at 19:51
  • The way you have done it in the question is the best way to do it, just manually put `''` around the variable names. There is no scenario where you would need this to be done dynamically. – Sayandip Dutta Aug 09 '20 at 19:55
  • `arr_name = [i for i in globals()]` will get you an array of those var names and whatever others are in `globals()`. If your code is simple, that might be usable. – GAEfan Aug 09 '20 at 20:14
  • @GAEfan, `list(globals())` will do the trick. – Olvin Roght Aug 09 '20 at 20:17

1 Answers1

-2
var_dict = {}

var_dict["abc"], var_dict["def"], var_dict["ghi"], var_dict["jkl"] = (1,2,3,4)
arr = list(var_dict)

print(arr)
#['abc', 'def', 'ghi', 'jkl']
Andreas
  • 8,694
  • 3
  • 14
  • 38