-3

I am writing a program for school and I have been wondering if there is a function that print variable names and not their values.

a=2131
b="sdfds"
c=[a, b]
print(c)

i want to print "a" and "b"

jst kiko
  • 113
  • 1
  • 4
  • 2
    Variables don't have names in Python. Names point to data. – internet_user Feb 08 '18 at 19:00
  • Your list does not contain the variables `a` and `b`. It is not possible for lists to contain variables in Python; variables and objects are two entirely separate categories of things. – user2357112 Feb 08 '18 at 19:04
  • 1
    Have a quick guide to how Python variables and objects work: https://nedbatchelder.com/text/names.html – user2357112 Feb 08 '18 at 19:04
  • You could of course just print the names if you know them (`c=['a','b']`), but then again, those are just objects that happen to be strings of the names of said variables. – kabanus Feb 08 '18 at 19:05

1 Answers1

-2

Try this method:

def what(var, locals=locals()):
    for name, value in list(locals.items()):
        if value is var:
            return name

Usage:

>>> a=2131
>>> b="sdfds"
>>> what(a)
'a'
>>> what(b)
'b'
>>> c=[a, b]
>>> for i in c:
...     what(i)
... 
'a'
'b'
>>> 
destresa
  • 117
  • 5