How to find the name of a list in a list of lists instead of its value?

Viewed 15870

I am trying to find the name of a list in a list of lists (is there a specific name for "list of lists"?).

For example I have the following lists:

x= ["a","b"]
y= ["c","d"]
z= [x,y] 

If I now want to know what is the name of the first list in list "z" I would try like that:

print(z[0])

But instead of "x" I get the value of x ("a","b")

  • How can I get the output "x"?
5 Answers

You want to use a dictionary instead of a list. Where a list is just an enumeration of values, a dictionary is a key-value data structure.

This is how your example would look as a dictionary literal:

{
    "x": ["a", "b"],
    "y": ["c", "d"],
}

Unlike a list, a dictionary does not preserve the order of elements however! If you had an application where you needed to preserve order, you can use an OrderedDict. UPDATE: This paragraph is no longer true as of Python 3.7.

Having the name of variable as your output is not possible, unless you change some strategies in your code, for e.g:

x = ["a", "b"]
y = ["c", "d"]
z = {'x': x, 'y': y}

using dictionaries might be better suited to your problem. You can then search for value ["a", "b"] and reach the name 'x'.

Maybe just put the list name at the start of each list and instead use z[0][0] to get the name?

a list is a mutable datatype in python. so with

x = ["a", "b"]

python will allocate some memory and store the adress in x. so x is internally something like:

<List with data at 0x123456789>

when you make z, python allocates some memory and stores the adress in z then, it will store the adresses of x and y in the memory of z. so z is internally:

[<List with data at 0x123456789>, <List with data at 0x987654321>]

now you can see that there is no information of the name of the variable which also stores the adress 0x123456789

Summary: you can't get the variable name of a list object.

Python3

#!/usr/bin/env python
#getGlobalNames.py
# Example Globals
someVar='foo';empty=[];someLst=['thing1','thing2']
def jam(treble=True,bass=11):someJam=(treble,base)
# Names you are looking for...
obs=[empty,someLst,jam]
# doStuff
globs=list(globals().items())# globals to static
oX=[]
for o in obs:
    for glob in globs:
        if glob[1]==o:oX.append(glob)
for o in oX:print('Name:',o[0],'\nStuff:\n',o[1])

Out:

RESTART: ./getGlobalNames.py
Name: empty 
Stuff:
 []
Name: someLst 
Stuff:
 ['thing1', 'thing2']
Name: jam 
Stuff:
 <function jam at 0x7f89f8e775e0>
>>> 
Related