0
0
NumPydata~5 mins

Views share memory with originals in NumPy

Choose your learning style9 modes available
Introduction

Views let you look at the same data without copying it. This saves memory and time.

When you want to change part of a big dataset without making a copy.
When you want to save memory by not duplicating data.
When you want fast access to a subset of data for calculations.
When you want to share data between different parts of your program.
When you want to avoid slow copying of large arrays.
Syntax
NumPy
view_array = original_array[start:stop]
# or
view_array = original_array.reshape(new_shape)

A view is created by slicing or reshaping an array.

Changes to the view affect the original array and vice versa.

Examples
This creates a view of elements 2, 3, and 4 from the original array.
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
view = arr[1:4]
This reshapes the 2x2 array into a 1D view of 4 elements.
NumPy
arr = np.array([[1, 2], [3, 4]])
view = arr.reshape(4)
Sample Program

This program shows that changing the view changes the original array because they share the same data.

NumPy
import numpy as np

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

# Create a view by slicing
view = original[1:4]

print('Original before change:', original)
print('View before change:', view)

# Change the view
view[0] = 99

print('Original after change:', original)
print('View after change:', view)
OutputSuccess
Important Notes

Not all operations create views; some create copies. Always check with np.shares_memory() if unsure.

Views are fast and memory efficient but be careful when modifying data to avoid unexpected changes.

Summary

Views let you access the same data without copying.

Changing a view changes the original array.

Use views to save memory and speed up your code.