I'm trying to create multiple lists like the following:
l1 = []
l2 = []
..
ln = []
Is there any way to do that?
I'm trying to create multiple lists like the following:
l1 = []
l2 = []
..
ln = []
Is there any way to do that?
What you can do is use a dictionary:
>>> obj = {}
>>> for i in range(1, 21):
... obj['l'+str(i)] = []
...
>>> obj
{'l18': [], 'l19': [], 'l20': [], 'l14': [], 'l15': [], 'l16': [], 'l17': [], 'l10': [], 'l11': [], 'l12': [], 'l13': [], 'l6': [], 'l7': [], 'l4': [], 'l5': [], 'l2': [], 'l3': [], 'l1': [], 'l8': [], 'l9': []}
>>>
You can also create a list of lists using list comprehension:
>>> obj = [[] for i in range(20)]
>>> obj
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>>
[[]]*20 instead of using the range function.[[]] * 20 gives you a list of 20 references for the inner [ ] instead, this is incorrect. Try appending 1 value into the list, all of them will have that values too. Indeed if L = [[]]*20 then L[0] is L[1] will be TrueCreate a list of lists:
lists = []
n = 20
for i in range(n):
lists.append([])
print lists[0] # Prints []
print lists[19] # Prints []
lists = [[] for _ in range(n)].Just Extending Already Accepted Answer, Using Enumerate to initiate default values in list. Accessing list and adding values which was not mentioned.
range_list = list(range (int(input())))
obj = {}
for i, j in enumerate(range_list): # assigning default values
obj['l'+str(i)] = [j**2]
print(obj['l0'])
print(type(obj['l0']))
obj['l0'] = list(range(5)) # accessing list
print(obj['l0'])
#3 asking user, how many list to be created
#[0] default value in first list
#<class 'list'>
#[0, 1, 2, 3, 4] current value in first list
#[Program finished]