Sometimes you want to change data without making a full copy to save memory. Other times, you want a separate copy to avoid changing the original data by mistake.
0
0
Controlling copy behavior in NumPy
Introduction
When you want to modify an array but keep the original unchanged.
When you want to save memory by working with views instead of copies.
When you want to pass data to a function without copying it.
When you want to create a backup of data before changing it.
When you want to avoid unexpected changes due to shared data.
Syntax
NumPy
array.copy() array.view()
copy() makes a full separate copy of the array data.
view() creates a new array object that looks at the same data (no copy).
Examples
This shows how to make a full copy and a view of the same array.
NumPy
import numpy as np arr = np.array([1, 2, 3]) arr_copy = arr.copy() # full copy arr_view = arr.view() # view, no copy
Changing
arr_copy does not affect arr, but changing arr_view does.NumPy
arr_copy[0] = 100 arr_view[1] = 200 print(arr) # original array
Sample Program
This program shows how changing the copy does not affect the original array, but changing the view does affect it because they share the same data.
NumPy
import numpy as np # Original array arr = np.array([10, 20, 30]) # Make a full copy arr_copy = arr.copy() # Make a view (no copy) arr_view = arr.view() # Change the copy arr_copy[0] = 999 # Change the view arr_view[1] = 888 print('Original array:', arr) print('Copy array:', arr_copy) print('View array:', arr_view)
OutputSuccess
Important Notes
Use copy() when you want to protect the original data from changes.
Use view() to save memory and speed when you only need to look at or temporarily change data.
Be careful: modifying a view changes the original array, which can cause bugs if unexpected.
Summary
copy() makes a full separate copy of the array data.
view() creates a new array object sharing the same data (no copy).
Choose copy or view depending on whether you want to protect original data or save memory.