0

I have lists such as:

list_1 = []
list_2 = []
list_3 = []

I want to put them all into a list where the list names are strings

list_final = ["list_1", "list_2", "list_3"]

Is there a simple way to do this?

Lazerhorse
  • 123
  • 1
  • 10
  • You may wish to look at the `dict` type: https://docs.python.org/3/tutorial/datastructures.html#dictionaries – DanielB May 24 '20 at 08:39
  • Can you please [edit] your question to clarify your expected output? ``[list_1, list_2, list_3]`` is not "a list where the list names are strings". Is your desired output ``["list_1", "list_2", "list_3"]``? Are you looking for a mapping from name to list, i.e. ``{"list_1": list_1, "list_2": list_2, "list_3": list_3}``? – MisterMiyagi May 24 '20 at 08:41
  • Does this answer your question? [How do I concatenate two lists in Python?](https://stackoverflow.com/questions/1720421/how-do-i-concatenate-two-lists-in-python) – azro May 24 '20 at 08:41
  • The answer is no. – Patrick Artner May 24 '20 at 08:42
  • try ask with exampl – Devanshu May 24 '20 at 08:42
  • This should answer your question: https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string – tanmay_garg May 24 '20 at 08:44
  • To be clear: You want to store *just* the names, *not* the values? Do you want to do this next to the assignment (e.g. inside the function defining them), or given just the lists (e.g. outside the function defining them)? Can you change the definition/assignment of the lists, e.g. to directly store them in a ``dict``? – MisterMiyagi May 24 '20 at 08:45

2 Answers2

2

Using a dict

my_lists = {
    "list_1": [],
    "list_2": [],
    "list_3": [],
}

The "names" ("keys" in terms of dict) are available as my_lists.keys() or by iterating my_lists:

for list_name in my_lists:
    print(list_name)

Or, for literally the sample given in the question:

list_final = list(my_lists)
DanielB
  • 2,798
  • 1
  • 19
  • 29
-1

The below shall work..

list = [list_1, list_2, list_3]
names=['list_1', 'list_2', 'list_3']
list_final = dict(zip(names,list))
print(list_final)
print(list_final['list_1'])
print(list_final['list_2'])
print(list_final['list_3'])

If you want to just put the names in the final list, you can do this:

list_final_names=[]
for name in list_final:
    list_final_names.append(name)
print(list_final_names)
Srinivas
  • 568
  • 1
  • 4
  • 21