Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

NumPy Array Copies and Views

NumPy provides different ways to work with array data. Sometimes an operation creates a separate array, while other operations create a view that shares memory with the original array. Understanding copies and views helps prevent unexpected changes and improves memory efficiency.

1. Introduction to Copies and Views

A NumPy array stores elements in memory. When you create another array from an existing array, NumPy may either copy the data or create a view of the same underlying data.

Copy

A copy creates a separate array with its own data buffer. Changes to the copied array do not change the original array's elements.

View

A view provides another way to access the same underlying data. Changes made through the view can affect the original array.

Copy Original Array Independent Data Changes stay separate View Shared Data Original and View Changes may be shared

A copy owns separate data; a view can share the original data.

2. Creating a NumPy Array Copy

Use the copy() method when you need an independent array whose element changes should not affect the original.

import numpy as np

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

copied = original.copy()

copied[0] = 999

print("Original:", original)
print("Copy:", copied)

Output

Original: [10 20 30 40]
Copy: [999  20  30  40]

The first element of copied changes to 999, while the original array remains unchanged.

Tip: Use array.copy() when you want to modify an array independently of its source.

3. Creating a View of an Array

The view() method creates a new array object that views the same underlying data. Changing an element through the view also changes the corresponding element in the original array.

import numpy as np

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

view_array = original.view()

view_array[1] = 777

print("Original:", original)
print("View:", view_array)

Output

Original: [ 10 777  30  40]
View: [ 10 777  30  40]

Both arrays show the updated value because they share the same underlying element data.

Important: A view is not a safe independent copy. If you modify shared elements through the view, the original can change.

4. Slicing and Memory Sharing

Basic slicing of a NumPy array generally returns a view rather than a separate copy. This makes slicing memory-efficient, but modifications to the slice can affect the source array.

import numpy as np

marks = np.array([65, 72, 80, 91, 55])

selected = marks[1:4]

selected[0] = 100

print("Original marks:", marks)
print("Selected slice:", selected)

Output

Original marks: [ 65 100  80  91  55]
Selected slice: [100  80  91]

The slice selects elements at indices 1, 2, and 3. Since it is a view, changing the first selected value also changes the value at index 1 in the original array.

Keep a Slice Independent

marks = np.array([65, 72, 80, 91, 55])

selected_copy = marks[1:4].copy()
selected_copy[0] = 100

print("Original marks:", marks)
print("Independent slice:", selected_copy)

Output

Original marks: [65 72 80 91 55]
Independent slice: [100  80  91]

5. Views and Copies with Different Operations

Different NumPy operations have different memory behavior. The following table shows common cases.

Operation Typical Result Memory Behavior
arr.copy() Copy Creates independent element data.
arr.view() View Shares underlying element data.
arr[1:4] Usually a view Basic slicing generally shares memory.
arr[[0, 2, 4]] Copy Advanced integer indexing creates a copy.
arr[arr > 20] Copy Boolean indexing creates a copy of selected data.
arr.reshape(...) View when possible May copy if the requested layout cannot be represented as a view.
Remember: Some operations can return a view in one situation and a copy in another. Check memory sharing when it matters.

6. Advanced Indexing Creates a Copy

Integer-array indexing and Boolean indexing create new arrays containing the selected values. Changes to these results do not change the original array's elements.

import numpy as np

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

integer_selected = numbers[[0, 2, 4]]
boolean_selected = numbers[numbers > 25]

integer_selected[0] = 999
boolean_selected[0] = 888

print("Original:", numbers)
print("Integer selection:", integer_selected)
print("Boolean selection:", boolean_selected)

Output

Original: [10 20 30 40 50]
Integer selection: [999  30  50]
Boolean selection: [888  40  50]

The original array remains unchanged because the selected arrays contain copied data.

7. Checking Whether Arrays Share Memory

NumPy provides np.shares_memory() to check whether two arrays share any memory locations for their elements. It returns a Boolean value.

import numpy as np

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

view_array = original[1:3]
copied_array = original[1:3].copy()

print(np.shares_memory(original, view_array))
print(np.shares_memory(original, copied_array))

Output

True
False

The slice shares memory with the original array, while the copied slice has independent element data.

Compare Array Objects

print(original is view_array)
print(original is copied_array)

Output

False
False

The is operator checks whether two variables refer to the exact same Python object. A view and its original are different array objects even when they share memory. Therefore, use np.shares_memory() to investigate shared element storage.

8. Copies and Views with Two-Dimensional Arrays

The same principles apply to two-dimensional arrays. A basic slice can share memory with the original matrix, while an explicit copy is independent.

import numpy as np

matrix = np.array([
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
])

matrix_view = matrix[:2, :2]
matrix_copy = matrix[:2, :2].copy()

matrix_view[0, 0] = 999
matrix_copy[0, 1] = 888

print("Original matrix:")
print(matrix)

print("View:")
print(matrix_view)

print("Copy:")
print(matrix_copy)

Output

Original matrix:
[[999  20  30]
 [ 40  50  60]
 [ 70  80  90]]

View:
[[999  20]
 [ 40  50]]

Copy:
[[999 888]
 [ 40  50]]

Updating matrix_view[0, 0] changes the original matrix. Updating matrix_copy[0, 1] does not change the original.

9. Practical Example: Student Marks

Suppose Samadhan, Pradnya, and Samiksha have examination marks. We want to create a separate set of marks for a practice exercise without changing the original records.

import numpy as np

student_names = np.array([
    "Samadhan",
    "Pradnya",
    "Samiksha"
])

original_marks = np.array([78, 85, 92])

# Create independent data for practice
practice_marks = original_marks.copy()

# Modify practice values
practice_marks[0] = 95
practice_marks[1] = 90

print("Students:", student_names)
print("Original marks:", original_marks)
print("Practice marks:", practice_marks)

Output

Students: ['Samadhan' 'Pradnya' 'Samiksha']
Original marks: [78 85 92]
Practice marks: [95 90 92]

The original marks are preserved because practice_marks was created with copy().

Best practice: Use copies when editing temporary data, testing calculations, or preparing independent datasets. Use views when shared access is intentional and you understand the side effects.

10. Common Mistakes

Mistake 1: Assuming a Slice Is Independent

arr = np.array([10, 20, 30, 40])
part = arr[1:3]
part[0] = 500

print(arr)

The original array changes because basic slicing generally returns a view. Use arr[1:3].copy() when independent data is required.

Mistake 2: Using a View When a Copy Is Needed

arr = np.array([1, 2, 3])
view_arr = arr.view()

view_arr[0] = 100

print(arr)

The first element of the original array also becomes 100. Use arr.copy() to isolate changes.

Mistake 3: Assuming Different Objects Never Share Memory

Two array objects can be different objects but still share element storage. Use np.shares_memory() when you need to check.

11. Practice Exercises

Exercise 1: Create a Copy

Create an array containing 5, 10, 15, and 20. Make a copy, change the first element of the copy, and print both arrays.

Exercise 2: Explore a View

Create an array containing 2, 4, 6, 8, and 10. Make a view, change one element through the view, and observe the original array.

Exercise 3: Test Memory Sharing

Create a basic slice and an explicit copy from the same array. Use np.shares_memory() to compare them with the original.

Exercise 4: Two-Dimensional Array

Create a 3 by 3 matrix. Extract a 2 by 2 slice, create a copy of that slice, and compare the effect of modifying each result.

Exercise 5: Student Marks

Create a marks array for Samadhan, Pradnya, and Samiksha. Make an independent copy for practice, update one mark, and confirm that the original marks remain unchanged.

Summary

NumPy copies and views determine how arrays share data in memory. A copy creates independent element data, while a view provides another way to access existing data.

Use array.copy() when changes must remain separate. Use array.view() when shared access is intended. Basic slicing generally returns views, while advanced integer indexing and Boolean indexing return copies.

Use np.shares_memory() to check whether arrays share memory. Understanding these behaviors helps prevent unexpected modifications and supports efficient NumPy programming.