What is a View?
A view is a new array object that shares the same data (memory) as the original array.
- No new memory is created
- Changes in the view affect the original array
- Faster and memory-efficient
Example :
Python
import numpy as np arr = np.array([10, 20, 30, 40, 50]) view_arr = arr[1:4] view_arr[0] = 999 print(arr) #output [ 10 999 30 40 50 ] Check if an Array is a View :
Python
import numpy as np arr = np.array([10, 20, 30, 40, 50]) view_arr = arr[1:4] view_arr[0] = 999 print(view_arr.base is arr) #output True What is a Copy?
A copy creates a new array with its own memory.
- Independent data
- Changes do NOT affect original array
- Uses more memory
Example :
Python
import numpy as np arr = np.array([10, 20, 30, 40, 50]) copy_arr = arr.copy() copy_arr[0] = 111 print(arr) print(copy_arr) #output [ 10 999 30 40 50 ] [111 999 30 40 50 ] Creating a Copy explicitly using copy( )?
Python
new_arr = arr.copy() #or new_arr = np.array(arr, copy=True)