Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a multidimensional list of a variable amount of dimensions in python?

I am trying to create a function that will make a multidimensional list taking an input number to choose the amount of dimensions the list will be. This is my code so far:

def createMultiDimList(dimensions, currentDim=0, output=[]):
    if currentDim < dimensions:
        output.append([])
        currentDim += 1
        createMultiDimList(dimensions, currentDim, output[0])
        return output
    else:
        return output

I think this isn’t working because the recursion is just putting in the single dimensional list, but I am not sure on that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re overcomplicating it IMO. The general idea behind recursion is to solve the easiest case first, and then return the result of the more difficult case in terms of an incrementally easier case.

For this function, the "easy case" is that a 1-dimensional list is []. The incrementally easier case is that an n-dimensional list is an n-1-dimensional list inside a list. Hence:

>>> def n_dim_list(n: int) -> list:
...     if n == 1:
...         return []
...     return [n_dim_list(n-1)]
...
>>> n_dim_list(4)
[[[[]]]]

If you wanted to complicate it a bit to make it a more interesting example of recursion, you could define a filler value for the 1-dimensional lists and the length of each list:

>>> def n_dim_list(n: int, length: int = 0, value = None) -> list:
...     if n == 1:
...         return [value] * length
...     return [n_dim_list(n-1, length, value) for _ in range(length or 1)]
...
>>> n_dim_list(4)
[[[[]]]]
>>> n_dim_list(4, 2, 0)
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading