I'm trying to create multiple lists like the following:
l1 = []
l2 = []
..
ln = []
Is there any way to do that?
You can simply use a for loop to create n lists. The variable a_i changes as i increments, so it becomes a_1, a_2, a_3 ... and so on.
Using + operator to append multiple lists at once This can be easily done using the plus operator as it does the element addition at the back of the list. Similar logic is extended in the case of multiple lists.
To create multiple empty lists: Use a list comprehension to iterate over a range object N times. Return an empty list on each iteration. The new list will contain N empty lists.
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
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>>
You can use dictionary comprehension:
obj = {i:[] for i in list(range(1,5))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With