-1

I want the output as variable and not its value. Below code gives me output as "what" "why" "when" "where" But I want the output as a b c d

a = "what"
b = "why"
c = "when"
d = "where"

A = [a,b,c,d]
for x in A:
    print (x)
  • Does this answer your question? [How to print original variable's name in Python after it was returned from a function?](https://stackoverflow.com/questions/544919/how-to-print-original-variables-name-in-python-after-it-was-returned-from-a-fun) – Leprechaun Aug 18 '20 at 22:52

2 Answers2

0

That is not really possible. If you want to also keep track of the names, you should use a dict:

words = { "a": "what", "b": "why", "c": "when", "d": "where" }

for x in words.keys():
    print(x)

The only way to also print out the variable name is the new debug formatting options in 3.8:

print(f"{x=}")

which would result in something like

x = 5
smelm
  • 1,253
  • 7
  • 14
0

https://docs.python.org/3/library/inspect.html

import inspect


def retrieve_variable_name(value):
    for var, val in inspect.currentframe().f_back.f_locals.items():
        if val is value:
            return var


a = "what"
b = "why"
c = "when"
d = "where"

A = [a, b, c, d]
for x in A:
    print(retrieve_variable_name(x))