1

I have no idea how to begin with this, but here's what I need. The user enters a number:

n = 3

This creates 'n' empty lists:

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

That is, create 'n' number of lists, based on the input by the user.

This seems like a simple enough problem, and I am sure that I need to create a for loop, but I don't know how to go about it.

for x in range(n):
    print(list_x = []) 

But this gives an obvious error:

'list_x' is an invalid keyword argument for print()

What I need is a sort of a "Create a list" function, but I don't know what it is.

I am sure there are other ways to solve my problem more elegantly, but I already have a simple solution that works, I just need to create an empty list for each step. I want to now generalize it, so that I don't have to have dozens of lists created at the beginning of the program.

Also, I am a beginner with coding, so please don't be too harsh :)

1 Answers1

1

You could make a dictionary, where each key is the name of the list, and each value contains an empty list.

n = 3
dic = {f'list{i}': [] for i in range(1, n+1)}
print(dic)

Output:

{'list1': [], 'list2': [], 'list3': []}
solid.py
  • 2,782
  • 5
  • 23
  • 30
  • What about a list of lists? – Mad Physicist Sep 23 '20 at 13:59
  • @MadPhysicist Sure thing, but this approach keeps the naming conventions of lists e.g list_1, list_2, list_3. I was about to edit a default dict approach – solid.py Sep 23 '20 at 14:00
  • This indeed created a list. But how do I access the list (I need to append to it)? I tried to use "list1", and I got an error saying "list1 is not defined" – Vikrant Srivastava Sep 24 '20 at 06:52
  • 1
    @VikrantSrivastava Good question. Type it `dic['list1']`. Mind the quotes. The keys are strings therefore it's `'list1'` not `list1` (without quotes). – solid.py Sep 24 '20 at 07:58