Home > Software engineering >  Are there any hidden changes if I change a numpy array that is a reference for another variable?
Are there any hidden changes if I change a numpy array that is a reference for another variable?

Time:03-15

this is just a question purely out of interest. I was learning numpy when I stumbled upon the difference between assigning an existing array to a variable and using numpy.copy().

import numpy as np

original = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
new = original[:, 0]
original[2, 2] = 69
print (new)
[ 1 4 7 10]

I know that if changes are made to the existing array (original), new will also have the same changes. But if I change something in original that is out of bounds for new, nothing will be changed in new. My question is, are there any hidden changes in new if this happens? Should I be concerned?

CodePudding user response:

original[:, 0] is a view on original. This means that both share the same memory buffer containing array values. Modifying one will affect the other. Technically, original is also a view and in Numpy you can never really manipulate array, only view on arrays. Numpy take care of the memory management of array for you. A view is a reference to an array, some offsets, some strides, a size and some low-level flags. Not much more. Modifying a values of an array using a view does not affect the other view objects themselves though the content of the views can be affected since they reference the same array (technically, view does not contain the values, only "hidden" referenced array).

Put is shortly: no, there is no other hidden change than the modified cell in the shared array.

CodePudding user response:

It might depend on what you would mean with "hidden" changes. What you have done when you assigned a part of original to new is that you made a view. Only that what is within your "scope" of new is changed. Underlying nothing changes that. As soon as you get into the "scope" of new inside original, you will start seeing changes reflected when you use new. Note, however, that new is not changed under the hood, because you look at a view.

  • Related