import numpy as np
old = no.array([[1, 1, 1], [1, 1, 1]])
new = old
new[0, :2] = 0
print(old)
(i) There is a typo in the second line, it should be
old = np.array([[1, 1, 1], [1, 1, 1]])
(ii) The script returns the array
[[0 0 1]
[1 1 1]].
This happens in python for memory optimization purposes. Line tree (new=old) creates a pointer that points to the same memory address and to the same object in memory. Then, when we change some values in new, we change the only one unique object shared for new and old, so when old is printed it is changed too.
To avoid this, two separate arrays are needed. This is called a deep copy. A copied array in this case will be a totally different object stored in another memory cell.
from copy import deepcopy
import numpy as np
old = np.array([[1, 1, 1], [1, 1, 1]])
new = deepcopy(old)
new[0, :2] = 0
print(old)
will print
[[1 1 1]
[1 1 1]]
Comments
Leave a comment