Skip to course content
Free course

Python Foundations / Module 8 / Copies, Views, and Mutation

Module 8 lesson

Copies, Views, and Mutation

Unit ID: M08-U07 Estimated active time: 25-35 minutes

Some selections are views into the same underlying data. Changing the view can change the source.

source = np.array([10, 20, 30, 40])
view = source[1:3]
view[0] = 99
print(source)  # [10, 99, 30, 40]

Use .copy() when the working array must be independent.

source = np.array([10, 20, 30, 40])
working = source[1:3].copy()
working[0] = 99
assert source.tolist() == [10, 20, 30, 40]

Boolean indexing commonly creates a copy, while basic slicing commonly creates a view. Do not rely on memory; make independence explicit when source preservation matters.

Practice: create a working copy, replace negative values with zero, and prove the source is unchanged.