output list object name in python

To output a list object name in Python, we can make use of the print statement and the id() function. The id() function returns the unique identifier of an object in Python.

Here's an example:

main.py
my_list = [1, 2, 3, 4, 5]

print("The name of the list object is:", [name for name in globals() if globals()[name] is my_list][0])
131 chars
4 lines

Output:

main.py
The name of the list object is: my_list
40 chars
2 lines

In the code above, we created a list my_list and then used a list comprehension to loop through all the objects in the global namespace and find the one with the same memory address as my_list. We then printed the name of the object using the print statement. This approach allows us to output the variable name of any object, not just lists.

gistlibby LogSnag