How To Create A List Of Empty Lists
Apologies if this has been answered before, but I couldn't find a similar question on here. I am pretty new to Python and what I am trying to create is as follows: list1 = [] list2
Solution 1:
For arbitrary length lists, you can use [ [] for _ in range(N) ]
Do not use [ [] ] * N
, as that will result in the list containing the same list objectN
times
Solution 2:
For manually creating a specified number of lists, this would be good:
empty_list = [ [], [], ..... ]
In case, you want to generate a bigger number of lists, then putting it inside a for loop would be good:
empty_lists = [ [] for _ in range(n) ]
Solution 3:
If you want a one-liner you can just do:
result = [[],[]]
Solution 4:
results = [[],[]]
or
results = [list(), list()]
Solution 5:
I would suggest using numpy because you can build higher-dimensional list of lists as well:
import numpy as np
LIST = np.zeros( [2,3] )# OR np.zeros( [2,3,6] )
It works in any number of dimensions.
Post a Comment for "How To Create A List Of Empty Lists"