-2

I have a nested list like this:

list1 = [1,2,3]
list2 = [4,5,6]

list_all = [list1,list2]

My question is in a for loop how to get the list1 and list2 as a name of the list:

for i in list_all:
    print(list1.name,list2.name)

Output should like:

"list1",'list2'
2
  • 1
    Your list_all is exactly equivalent to [[1,2,3],[4,5,6]] - there is absolutely no way to tell that the sub-lists came from individual variables, rather than being written directly in the assignment. Commented May 3, 2021 at 21:35
  • 2
    Related: Getting the name of a variable as a string Commented May 3, 2021 at 21:37

2 Answers 2

3

If you make the lists dictionaries you can provide a name

list1 = { "name": list1, "list": [1,2,3]}
list2 = { "name": list2, "list": [4,5,6]}

list_all = [list1,list2]

for i in list_all:
    print(list_all[i].name)
Sign up to request clarification or add additional context in comments.

Comments

1

It's a bit complicated and inefficient but it works:

list1 = [1,2,3]
list2 = [4,5,6]
list_all = [list1,list2]
i = k = v = None 
# we need this line to avoid "RuntimeError: dictionary changed size during iteration" so locals() will recognize them
loc = locals().items()

for i in list_all:
 for k,v in loc:
  if v is i and k != 'i':
    # if id(v) equal to id(i)
    print(k)

and the output will be:

list1
list2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.