Suppose I start with a list as initial_list = [None] * 4
. By setting depth = D
, how can I define a routine to create a nested list of arbitrary depth in such way that each entry of the first list admits x-1
levels, being each level itself a list of other 4 elements. Something that afterwards would allow to slice data as for example myPrecious[0][0][3][0]
,myPrecious[3][2][1][0]
,... ?
You can use list comprehensions in a loop:
import copy
def build_list(depth, nb_per_level, fill=0):
l = [fill for _ in range(nb_per_level)]
for _ in range(depth):
l = [copy.deepcopy(l) for _ in range(nb_per_level)]
return l
>>> build_list(2, 3, 7)
[[[7, 7, 7], [7, 7, 7], [7, 7, 7]], [[7, 7, 7], [7, 7, 7], [7, 7, 7]], [[7, 7, 7], [7, 7, 7], [7, 7, 7]]]
>>> build_list(1, 5, 7)
[[7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7], [7, 7, 7, 7, 7]]
>>> build_list(0, 5, 7)
[7, 7, 7, 7, 7]
>>> my_precious = build_list(3, 4, 7)
>>> my_precious[3][2][1][0]
7
Note the importance of copy.deepcopy(l)
in the list comprehension, rather than just l
, which makes a copy of the list instead of reusing the same list. Related question about the danger of not making a deepcopy: List of lists changes reflected across all lists unexpectedly?