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)
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)
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
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))