NumPy Array Copy vs View

🆚 NumPy — Copy vs View

When working with NumPy arrays, modifying data may or may not affect the original array depending on whether you’re using a copy or a view.

Feature Copy View
Separate memory? ✅ Yes ❌ No
Changes affect original? ❌ No ✅ Yes
Faster? ❌ Slightly slower ✅ Faster
Use case When original data must be preserved Memory-efficient slicing & referencing

📌 1. Copy (Creates a New Array)

A copy creates a completely independent array.

import numpy as np

arr = np.array([10, 20, 30, 40])
cpy = arr.copy()

cpy[0] = 99

print(arr) # Original remains unchanged
print(cpy)

Output:

[10 20 30 40]
[99 20 30 40]

📌 2. View (Shares Data With Original)

A view does NOT create a new memory; it references the original data.

arr = np.array([10, 20, 30, 40])
vw = arr.view()

vw[1] = 88

print(arr) # Original changed
print(vw)

Output:

[10 88 30 40]
[10 88 30 40]

🎯 Checking the Relationship: base Attribute

You can check whether an array owns its data using the .base property.

print(cpy.base) # None → means COPY owns data
print(vw.base) # Reference to original array

📌 Example with 2-D Arrays

arr2 = np.array([[1, 2, 3], [4, 5, 6]])

vw2 = arr2.view()
vw2[0,1] = 99

print(arr2)
print(vw2)

Result: Both change because vw2 is a view.


📌 Slicing Creates a View (Not Copy)

arr = np.array([10, 20, 30, 40, 50])

slice_arr = arr[1:4] # This is a VIEW
slice_arr[0] = 999

print(arr)
print(slice_arr)


📌 To Force a Copy of a Slice

safe_slice = arr[1:4].copy()
safe_slice[0] = 555

print(arr) # Not affected
print(safe_slice)


🧠 When to Use What?

Use Case Best Option
Working with large datasets View (memory efficient)
Need independent data Copy
Slicing for temporary use View
Prevent accidental modification of original data Copy

📝 Summary

Feature Copy View
Memory usage More Less
Speed Slower Faster
Shares data ❌ No ✅ Yes
Uses .copy()? Yes No (views usually created by slicing)

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *