WHAT IS THE DIFFERENCE BETWEEN COPY AND VIEW OF AN ARRAY IN PYTHON NUMPY?

The main difference between a copy and a view of an array is that the copy is a new array and it owns the data, and the view is just a view of the original array and it doesn’t own the data.

The copy owns the data where as the view does not own the data.

Any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy.

Any changes made to the view will affect the original array, and any changes made to the original array will affect the view.

How to check whether an array owns its data or not?

We can check whether an array owns its data or not by using the NumPy attribute- base. The attribute base returns None if the array owns the data. Otherwise, the base attribute refers to the original object.

import numpy as np

arr = np.array([1, 2, 3, 4])

x = arr.copy()
y = arr.view()

print(x.base)
print(y.base)

Output-

None
[1 2 3 4]

Posted

in

Tags:

Comments

Leave a Reply