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 :)

3
  • 4
    Do those lists need to be individual variables? You could generate a list of lists with as many as you need. Commented Sep 23, 2020 at 13:55
  • If you have multiple things indexed by a number, think list. If indexed by something else, think dict. Commented Sep 23, 2020 at 13:57
  • @Mikael I am not sure if I understand you, but each list needs to be able to hold different elements... Commented Sep 24, 2020 at 6:57

1 Answer 1

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': []}
Sign up to request clarification or add additional context in comments.

4 Comments

What about a list of lists?
@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
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"
@VikrantSrivastava Good question. Type it dic['list1']. Mind the quotes. The keys are strings therefore it's 'list1' not list1 (without quotes).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.