0

I want to work through a list of n entries to create n new lists, naming the new lists after each n. My code would be something like:

nice_list = ("entry1", "entry2")

for n in nice_list:
    n_list = ()

but i know that this will give me n_list = () overridden n times. but the output i want is like:

entry1_list = ()
entry2_list = ()

I don't know how to extract the information that n represents to be able to name my lists automatically.

TIA

Helen
  • 3
  • 4

3 Answers3

0

I would recommend you to create a dictionary while each entry is a list:

nice_list = ("entry1", "entry2")
d = {}
for n in nice_list:
    d[n] = []
d

Output

{'entry1': [], 'entry2': []}
Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

If you want it to be a global variable, you can do something like:

for n in nice_list:
    globals()[n + '_list'] = []

If it a local variable (as, in a function or so), you could do the same with locals. But it is not guaranteed to work.

For that, you would have to do something hacky like exec,

for n in nice_list:
    exec(n + "_list = []")

But these are all hacky. You should use a dict for it.

noteness
  • 2,440
  • 1
  • 15
  • 15
0

Use dictionary for this:

nice_list = ["entry1", "entry2"]

dictionary = dict()
for n in nice_list:
    dictionary[n + "_list"] = []

print(dictionary)

If you want to fill the lists in the dictionary, easily done by appending it:

dictionary["entry1_list"].append("new_entry")

print(dictionary)

To make txt files with the name of the dict keys and each holding the values of said key:

for key in dictionary:
    with open(key + ".txt",'w') as file:
        for value in dictionary[key]:
            file.write('{}'.format(value))
Burnstrike
  • 71
  • 4
  • Thanks for the suggestions guys, but in the end i also need to save the contents to a txt file, and i want n to also be used to name the files automatically. Is a dictionary also suitable for this? I only really use the original to work through the variables automatically instead of running the code manually n times. I don't want to have to manually input n as my original list might change and i wanted it all to amend automatically. – Helen May 24 '20 at 15:19
  • Just to clarify: You want to make txt files with each one being the name of the dictionary key - and you want each txt file to contain the values that are associated to that dictionary key? If so, I've edited the code above to include it. – Burnstrike May 24 '20 at 16:02
  • Thankyou! That's great. – Helen May 26 '20 at 20:18