Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple lists

Tags:

python

list

I'm trying to create multiple lists like the following:

l1 = []  
l2 = []  
..  
ln = []  

Is there any way to do that?

like image 544
Sathish Bowatta Avatar asked Jun 02 '14 17:06

Sathish Bowatta


People also ask

How do you make multiple lists in Python?

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.

How do I add multiple lists to a list?

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.

How do you create multiple empty lists in Python?

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.


2 Answers

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
[[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
>>> 
like image 167
A.J. Uppal Avatar answered Oct 04 '22 01:10

A.J. Uppal


You can use dictionary comprehension:

obj = {i:[] for i in list(range(1,5))}
like image 28
Cindyleee Avatar answered Oct 04 '22 00:10

Cindyleee