0
0
NumPydata~5 mins

View vs copy behavior in NumPy

Choose your learning style9 modes available
Introduction

Understanding views and copies helps you avoid mistakes when changing data. It shows if you are changing the original data or just a separate copy.

When you want to change part of a large dataset without copying all data to save memory.
When you want to keep the original data safe and work on a separate copy.
When you slice or select data and want to know if changes affect the original array.
When debugging unexpected changes in your data after slicing or indexing.
When optimizing code to avoid unnecessary copying of large arrays.
Syntax
NumPy
view_array = original_array.view()
copy_array = original_array.copy()

view() creates a new array object but shares the same data.

copy() creates a new array with its own data, independent of the original.

Examples
This creates an original array, a view, and a copy.
NumPy
import numpy as np

arr = np.array([1, 2, 3, 4])
view_arr = arr.view()
copy_arr = arr.copy()
Changing the view also changes the original array because they share data.
NumPy
view_arr[0] = 100
print(arr)
Changing the copy does not affect the original array.
NumPy
copy_arr[0] = 200
print(arr)
Sample Program

This program shows how changing the view changes the original array, but changing the copy does not.

NumPy
import numpy as np

# Create original array
arr = np.array([10, 20, 30, 40])

# Create a view and a copy
view_arr = arr.view()
copy_arr = arr.copy()

# Change first element in view
view_arr[0] = 999

# Change first element in copy
copy_arr[0] = 555

# Print all arrays to see effects
print('Original array:', arr)
print('View array:', view_arr)
print('Copy array:', copy_arr)
OutputSuccess
Important Notes

Views share the same data buffer, so changes reflect in both arrays.

Copies have their own data, so changes do not affect the original.

Not all slicing returns a view; sometimes it returns a copy depending on the operation.

Summary

Views share data with the original array; copies do not.

Changing a view changes the original array.

Use copy() to work independently without affecting original data.