I want to create a multidimensional array and initialize it with copies of a mutable object. This is what I have so far:
import copy
def create_array(dimensions):
dimensions = copy.deepcopy(dimensions)
dimensions.reverse()
a = [0] * dimensions[0]
del dimensions[0]
for d in dimensions:
a = [copy.deepcopy(a) for _ in range(d)]
return a
def create_array_mutable(dimensions, obj):
a = create_array(dimensions)
def set(x):
if isinstance(x[0], list):
for e in x:
set(e)
else:
for i in range(len(x)):
x[i] = copy.deepcopy(obj)
set(a)
return a
I wonder if there is a better way to do it (without the copies and the recursion)?