[Tutor] silly remedial question

Michael Janssen Janssen at rz.uni-frankfurt.de
Mon Nov 24 09:25:43 EST 2003


On Mon, 24 Nov 2003, kevin parks wrote:

> I can print the input and output lists no problem, but how do you tell
> python to print the variable itself..

You can do it for *function* via their __name__ attribute:

def f():
    pass

print f.__name__

but variables havn't got such a attribute (they have no attributes at
all - it makes no sense to speak of an "attribute of a variable"). I
believe, it's not possible, to retrieve to name of a variable.
You should better store your list within a dictionary (i.e. a mapping
from  keys to values, in this case from names to lists):

d = { "name1": [];
      "name2": [];
      .....
    }

Now your task is easy:

for key in d.keys():
    print key, print d[key]


In case you can't rebuild your lists into a dictionary, you can (mis)use
the globals-dictionary:

d = globals()
for key in d:
    if type(d[key]) == type([]):
        print key, print d[key]


this will print out every list within global namespace (type "globals()"
on an interactive prompt, to get an idea what this means). Since the
globals-dictionary contains every list that is assinged it might print
out unwanted stuff. Regard this as a "bad hack" and try to write
programs, that don't need to get the "name of a variable".


Michael




More information about the Tutor mailing list