Yo, I have a problem with function which is made for converting list of objects to list of str to be witten to json file. I copy that original list and send it to function, but the function still rewrites the original one. Here is the code
columns = [
[Stone("O"),Stone("O")],
[],
[],
[],
[],
[Stone("X"),Stone("X"),Stone("X"),Stone("X"),Stone("X")],
[],
[Stone("X"),Stone("X"),Stone("X")],
[],
[],
[],
[Stone("O"),Stone("O"),Stone("O"),Stone("O"),Stone("O")],
[Stone("X"),Stone("X"),Stone("X"),Stone("X"),Stone("X")],
[],
[],
[],
[Stone("O"),Stone("O"),Stone("O")],
[],
[Stone("O"),Stone("O"),Stone("O"),Stone("O"),Stone("O"),],
[],
[],
[],
[],
[Stone("X"),Stone("X")]
]
def save(array):
i = 0
j = 0
print("Saving....")
while i < len(array):
while j < len(array[i]):
if array[i][j].Char == "O":
array[i][j] = "O"
elif array[i][j].Char == "X":
array[i][j] = "X"
else:
continue
j+=1
i+=1
j=0
print("Saved!")
array = json.dumps(array)
jsonFile = open("save.json", "w")
jsonFile.write(array)
jsonFile.close()
arr = columns.copy()
save(arr)
print(columns[0][0])
the output should throw memory address of columns[0][0], because there is an object, but it throws 0, because the object is replaced in function "save"
I tried to comment line with "save(arr)" and the result is what i need but it doesnt save data into json obviously. Also tried to check ids of lists and arr = columns.copy() has different id than columns, but it still rewrites it
>Solution :
You’ve have a list of lists. You’ve copied the top-level, but not the inner lists. Consider the below simple example where we perform both a shallow and a deep copy on a list of lists.
>>> a = [[1,2,3], [4,5,6]]
>>> b = a.copy()
>>> b[0][2] = 'foo'
>>> a
[[1, 2, 'foo'], [4, 5, 6]]
>>> import copy
>>> a = [[1,2,3], [4,5,6]]
>>> b = copy.deepcopy(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b[0][2] = 'foo'
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 'foo'], [4, 5, 6]]
Further, checking the IDs of the objects.
>>> a = [[1,2,3], [4,5,6]]
>>> b = a.copy()
>>> id(a[0])
139979290199944
>>> id(b[0])
139979290199944
>>> a = [[1,2,3], [4,5,6]]
>>> b = copy.deepcopy(a)
>>> id(a[0])
139979230660360
>>> id(b[0])
139979230762632