NUMPY Tutorial



NumPy COPY VS VIEW


πŸ”Ή NumPy Copy vs View

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.

1. What is a 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.

  • Changing data in the view will affect the original array, and vice versa.
  • The view is like a β€œwindow” into the original array’s data.

Example of View

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]

2. What is a Copy?

A copy creates a completely new array with its own separate data in memory.

  • Modifying the copy does NOT affect the original array.
  • Modifying the original does NOT affect the copy.

Example of Copy

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]

3. How to Check if Two Arrays Share Data?

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

4. When to Use View vs Copy?

  • Use a view if you want a new array object but don’t want to duplicate data β€” this saves memory and is faster.
  • Use a copy if you want to modify the new array without affecting the original.

5. Summary Table

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)

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review