How to create multiple empty nested lists in python

I want to have a variable that is a nested list of empty lists that I can populate later. Something similar:

my_variable=[[], [], [], []] 

However, I do not know in advance how many lists I need, only at the creation stage, so I need the variable a to define it. I thought of a simple my_variable=[[]]*a , but this creates copies of the lists, and this is not what I want to have.

I could do:

 my_variable=[] for x in range(a): my_variable.append([]) 

but I'm looking for a more elegant solution (preferably a single line). Whether there is a?

+7
python list nested-lists
source share
2 answers

Try a list comprehension :

 lst = [[] for _ in xrange(a)] 

See below:

 >>> a = 3 >>> lst = [[] for _ in xrange(a)] >>> lst [[], [], []] >>> a = 10 >>> lst = [[] for _ in xrange(a)] >>> lst [[], [], [], [], [], [], [], [], [], []] >>> # This is to prove that each of the lists in lst is unique >>> lst[0].append(1) >>> lst [[1], [], [], [], [], [], [], [], [], []] >>> 

Note that this is above for Python 2.x. On Python 3.x., since xrange been removed, you will need the following:

 lst = [[] for _ in range(a)] 
+12
source share
 >>>[[] for x in range(10)] #To make a list of n different lists, do this: [[], [], [], [], [], [], [], [], [], []] 

Edit: -

 [[]]*10 

This will give you the same result as above, but the list is not a separate instance, it is just n references to the same instance.

+6
source share

All Articles