In NumPy, both copy()
and view()
create new arrays from existing ones but differ in how they handle the underlying data in memory. Understanding this difference is key to writing efficient code and avoiding unexpected side-effects.
View
?A view
is a new array object that looks at the same data of the original array. No data is copied in memory β both arrays share the same data buffer.
import numpy as np
arr = np.array([1, 2, 3, 4])
v = arr.view()
v[0] = 100
print("Original array:", arr)
# Output: Original array: [100 2 3 4]
arr[1] = 200
print("View array:", v)
# Output: View array: [100 200 3 4]
Copy
?A copy
creates a completely new array with its own separate data in memory.
arr = np.array([1, 2, 3, 4])
c = arr.copy()
c[0] = 100
print("Original array:", arr)
# Output: Original array: [1 2 3 4]
arr[1] = 200
print("Copy array:", c)
# Output: Copy array: [100 2 3 4]
You can check if two arrays share the same data buffer by using the np.shares_memory()
function.
print(np.shares_memory(arr, v)) # True β view shares memory
print(np.shares_memory(arr, c)) # False β copy does not share memory
Feature | View | Copy |
---|---|---|
Data sharing | Shares same data buffer | Own separate data copy |
Effect of modifying new array | Changes original array | No effect on original array |
Memory use | Less memory (no copy) | More memory (copy created) |
Speed | Faster to create | Slower to create (copy cost) |
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!