/Curriculum/IntermediateMemory & Performance

27. NumPy Copy & ViewIntermediate

Understand memory sharing, arr.base, and when modifying a view alters original data.

15 mins

Concept Overview

A **view** shares the exact same memory buffer as the original array (zero-copy). A **copy** allocates a completely independent new memory buffer in RAM.

Hardware Mental Model

A **View** is looking at your friend's document through a magnifying glass (if your friend edits it, you see the change). A **Copy** is photocopying the document so you can scribble on your own copy without altering the original.

Key Concepts (1)Click snippet to load in editor

If `arr.base is None`, the array owns its memory buffer. If `arr.base` points to another array, it is a zero-copy view.

is_view = arr_slice.base is not None

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:b = a; b[0] = 99 # Both 'a' and 'b' refer to the exact same variable!
✓ Correct:b = a.copy(); b[0] = 99

`b = a` creates an alias variable name, not a copy. Modifying `b` will modify `a`.

Pro Tip: Always use `a.copy()` to make an independent data duplicate.

📌 Quick Revision

Core takeaway points from this topic
Views share memory buffers: changes in one reflect in the other.
Basic slices are views; `.copy()` creates independent memory.
`arr.base`: Shows None if array owns its data, or parent object if it's a view.
Editor: 27. NumPy Copy & View
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Create an Independent Array Copy

Create `a = np.array([1, 2, 3])`, create an independent copy `b = a.copy()`, set `b[0] = 99`, and print `a`.

Expected Output Target:[1 2 3]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state