NumPy Copy vs View
The copy() and view() methods look similar but decide whether an array owns its own data or merely borrows someone else's.
Copy vs View in NumPy
When you slice or transform a NumPy array, you sometimes get an independent array and sometimes get a window onto the original data. The copy() method always makes a new, independent array, while view() creates a new array object that still points at the same underlying memory as the original. Knowing which one you have prevents subtle bugs where editing one array silently changes another.
The Copy Owns Its Data
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
# Output:
# [42 2 3 4 5]
# [ 1 2 3 4 5]The View Shares Its Data
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)
# Output:
# [42 2 3 4 5]
# [42 2 3 4 5]Changing arr after making the view changes x too, because a view is just another label for the same block of memory. Changing arr after copy() leaves the copy completely untouched, since it allocated its own memory the moment copy() ran.
Checking Ownership With the base Attribute
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
copy_arr = arr.copy()
view_arr = arr.view()
print(copy_arr.base)
print(view_arr.base)
# Output:
# None
# [1 2 3 4 5]Exercise: NumPy Copy vs View
What is the key difference between a copy and a view in NumPy?