I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items.
Each list value should be initialized to
I found that to get what you mean you need to youse
import copy
def n_dim_list(dims, init_val):
if not dims:
return []
lst = [init_val for i in range(dims[-1])]
for d in dims[::-1][1::]:
lst = [copy.deepcopy(lst) for i in range(d)]
return lst
Where dims is a list of length of the number of the dimentions you want and the content is the size of the requiered nd-list in every dimention. Not the most elegant but clear and does the job.
You might actually need an array instead of some lists. Almost every time I see this "presized nested list" pattern, something is not quite right.
You can do it quite efficiently with a list comprehension:
a = [[0] * number_cols for i in range(number_rows)]
Yet another method, but using the OP's rejected method.
import numpy as np
myList = [[0]*10]*10
myList = np.array(myList)
l=myList.tolist()
myList=l
The output and testing below:
>>> l
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
>>> l[0][0]=100
>>> l
[[100, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
The output is unlike the expected clone of l[0]
.
Although this is not time efficient. It takes nearly 7 seconds for a 1000X1000 list, where as list comprehensions took only 0.0052158 seconds for the same.
Two common and short way to do this:
First:
[[0] * n] * m
Second:
[[0 for column in range(n)] for row in range(m)]
Just thought I'd add an answer because the question asked for the general n-dimensional case and I don't think that was answered yet. You can do this recursively for any number of dimensions with the following example:
n_dims = [3, 4, 5]
empty_list = 0
for n in n_dims:
empty_list = [empty_list] * n
>>>empty_list
>>>[[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]]