Copy vs View in NumPy
When working with NumPy arrays, understanding how data is stored in memory is extremely important. Some operations create a copy of data, while others create a view that shares the same memory.
This lesson explains the difference clearly, with real examples and outputs.
Why Copy vs View Matters
Knowing whether an operation creates a copy or a view helps you:
- Avoid unexpected data changes
- Improve performance and memory usage
- Write safer and more efficient code
- Debug data-related issues faster
Original Array
Let’s start with a simple NumPy array.
import numpy as np
data = np.array([10, 20, 30, 40, 50])
print(data)
Output:
[10 20 30 40 50]
What Is a View?
A view is a new array object that looks at the same underlying data in memory. Changing a view also changes the original array.
view_array = data.view()
view_array[0] = 999
print("View:", view_array)
print("Original:", data)
Output:
View: [999 20 30 40 50]
Original: [999 20 30 40 50]
Both arrays changed because they share the same memory.
Checking Memory Sharing
You can check whether arrays share memory using
np.shares_memory().
np.shares_memory(data, view_array)
Output:
True
What Is a Copy?
A copy creates a completely new array with its own memory. Changes to the copy do not affect the original array.
copy_array = data.copy()
copy_array[1] = 777
print("Copy:", copy_array)
print("Original:", data)
Output:
Copy: [999 777 30 40 50]
Original: [999 20 30 40 50]
The original array remains unchanged.
Memory Check for Copy
np.shares_memory(data, copy_array)
Output:
False
Common Operations That Create Views
- Slicing arrays
- Using
view() - Reshaping (in many cases)
Example with slicing:
sliced = data[1:4]
sliced[0] = 111
print("Sliced:", sliced)
print("Original:", data)
Common Operations That Create Copies
copy()- Advanced indexing
- Some mathematical operations
When to Use Copy vs View
- Use view when performance and memory efficiency matter
- Use copy when you want data safety
- Always be cautious when modifying sliced arrays
Practice Exercise
Exercise
Create a NumPy array and:
- Create a view and modify it
- Create a copy and modify it
- Observe how the original array changes
Expected Outcome
You should clearly understand how memory sharing works in NumPy.
What’s Next?
In the next lesson, you will learn about broadcasting and how NumPy performs operations on arrays with different shapes.