[Tutor] List's name in a string
Jeff Shannon
jeff at ccvcorp.com
Mon Sep 29 20:31:52 EDT 2003
Héctor Villafuerte D. wrote:
> Hi!
> is there a way to get a list's (or any variable) name in a string?
>
> For example:
> >>> list1 = [1, 2, 3]
> I would like to do something like this:
> >>> var = list1.name()
> So that var contains 'list1'.
You can sortof force it by going through locals() and globals(), but a
better approach would probably be to look again at *why* you want this.
Most of the time, if you need to refer to some variable name
programmatically like this, what you're really looking for is a list
or a dictionary. In other words, you typically want to refer to
variables by a variable name so that you can select one object from a
set of possible objects based on some runtime parameter. That's
exactly the niche that dictionaries fit. For example,
>>> data = {}
>>> data['list1'] = [1, 2, 3]
>>> data['list2'] = [4, 5, 6]
>>> data
{'list1': [1, 2, 3], 'list2': [4, 5, 6]}
>>> key = 'list1'
>>> data[key]
[1, 2, 3]
>>>
Maybe if you explain a bit more about your intent, we can explore an
easier way to accomplish your goal than mucking about in the
interpreter's innards.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list