0

I try to create a multidimensional array in python 3.7. Unfortunately I do not know the variable type, the dimensions or the amount of dimensions beforehand. My approach so far is a loop:

dimensions = [3,3]
vartype = 'binary'

if vartype=='binary':
    new_array=False
elif vartype=='int':
    new_array=0

for dim in dimensions:
    new_array = [new_array for _ in range(dim)]

The issue is, that if there is more than 1 dimension I end up with multiple references to the first dimension:

new_array[0][1]=True
print(new_array)

[[False, True, False], 
 [False, True, False],   
 [False, True, False]]

This has been addressed quite some times like here. In other cases however the amount of dimensions is known, so I can't transfer the solution to my problem. Does anyone know a way to create arrays of varying amount of dimensions?

Finn
  • 2,333
  • 1
  • 10
  • 21

2 Answers2

3

You can use the fact that the constructors for bool and int return the default values for those data types when invoked without an argument, i.e. bool() is False and int() == 0.

To make things generic for any number of dimensions, you could use a bit of clever recursion...

def make_array(dimension, element_ctor):
    return [element_ctor() for x in range(dimension)]


def make_ndim_array(dimensions, element_ctor):
    return make_array(
        dimensions[0],
        (
            element_ctor
            if len(dimensions) == 1
            else lambda: make_ndim_array(dimensions[1:], element_ctor)
        ),
    )


print(make_ndim_array([2, 3, 4], int))
print(make_ndim_array([3, 3], str))

outputs

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

Since element_ctor can be any function that can be invoked without an argument, you can even use this for an n-dimensional array of random numbers...

import random
print(make_ndim_array([2, 4, 11], random.random))
AKX
  • 152,115
  • 15
  • 115
  • 172
0
import copy

for dim in dimensions:
    new_array = [copy.deepcopy(new_array) for _ in range(dim)]
Maarten-vd-Sande
  • 3,413
  • 10
  • 27