I use the following function to create a multidimensional list of shape dimension
:
def create(dimensions, elem):
res = elem
for i in dimensions[::-1]:
res = [copyhelp(res) for _ in range(i)]
return res.copy()
def copyhelp(r): #when res begins as elem, it has no .copy() function
if isinstance(r,list):
return r.copy()
return r
So if I say mylist = create([3,3,2],0)
, I get
>> mylist
[[[0, 0], [0, 0], [0, 0]],
[[0, 0], [0, 0], [0, 0]],
[[0, 0], [0, 0], [0, 0]]]
Great. Now I use this function to change the value at an index given by a list index
to v
:
def replacor(array, index, v):
if not isinstance(array[0],list):
array[index[0]] = v
else:
return replacor(array[index[0]], index[1:], v)
Now when I do replacor(mylist, [1,2,0], '.')
, I get this:
>> mylist
[[['.', 0], [0, 0], [0, 0]],
[['.', 0], [0, 0], [0, 0]],
[['.', 0], [0, 0], [0, 0]]]
I'm suspicious it has to do with array pointers, but I used copy()
at every step, so I'm not sure where I went wrong. Clearly the issue is the way I define my first list, but I still don't understand why I'm getting this behavior since ints, bools, and strings are immutable.