1

Consider the following code:

x,y = 0,1
for i in [x,y]:
   print(i) # will print 0,1

Suppose I wanted instead to print:

x=0
y=1

I realise f-strings can be used to print the intermediate variable name:

for i in [x,y]:
    print(f"{i=}") # will print i=0, i=1

However, I am interested in the actual variable name.

There are other workarounds: using eval or using zip([x,y], ['x', 'y']), but I was wondering if an alternative approach exists.

SultanOrazbayev
  • 14,900
  • 3
  • 16
  • 46
  • 1
    You'd need to hardcode it. But given you're the one writing the code anyway, that shouldn't be a problem. – Green Cloak Guy Dec 21 '21 at 06:27
  • 1
    Use a dictionary. – Kelly Bundy Dec 21 '21 at 06:28
  • 1
    I suppose you could check `locals()`/`globals()` and try to figure out which name corresponds to the value you have, but that leaves room for error if multiple variables have the same value, and again, when you're the one writing the code there really isn't any point. – Green Cloak Guy Dec 21 '21 at 06:28
  • 1
    How about reference this answer? https://stackoverflow.com/a/59364138/10998724 and https://stackoverflow.com/a/18425523/10998724 – SEUNGFWANI Dec 21 '21 at 06:29
  • 1
    @SEUNGFWANI thank you, these are what I was looking for, though it turns out the answer is not so simple! – SultanOrazbayev Dec 21 '21 at 06:33

1 Answers1

0

I think this achieves what you want to do -

for i in vars():
    print(f'{i}={vars()[i]}')
sr0812
  • 324
  • 1
  • 9