Search code examples
pythonpython-3.xnested-lists

Is there a way to create multiple nested lists to a certain depth?


I apologise if the question is indirect or confusing. What I'm trying to achieve is a list like the one below:

[[[0,0],[0,0],[0,0]],[[0,0],[0,0],[0,0]],[[0,0],[0,0],[0,0]]]

However, I want the list to have a variable amount of list "depth" (the above list has a list "depth" of 3 since it a maximum of 3 lists at the bottom; to access an item in it it would look like `aList[1][0][1]` )

I have tried using list comprehension:

aList = [[[[None for _ in range(3)] for _ in range(3)] for _ in range(3)] for _ in range(3)]

The only problem with this is that I can't change the depth of the list without directly editing the code.

What can I do to achieve the result I'm after? (The list I am trying to achieve contains 7^4 (2401) items, just so you're aware.)


Solution

  • This might be a nice job for :

    import numpy as np
    
    out = np.zeros((3, 3, 2), dtype=int).tolist()
    

    Output:

    [[[0, 0], [0, 0], [0, 0]],
     [[0, 0], [0, 0], [0, 0]], 
     [[0, 0], [0, 0], [0, 0]]]
    

    Or with a recursive function:

    def nested(shape):
        if shape:
            n, *shape = shape
            return [nested(shape) for _ in range(n)]
        return 0
    
    out = nested((3, 3, 2))