NumPy view vs copy: how to tell which an operation returns, and why it matters for aliasing bugs

Quick Overview

Asks how NumPy views differ from copies, how to tell which one an operation returns, and why the difference causes aliasing bugs. Tests buffer sharing, slicing versus fancy indexing, the base attribute and np.shares_memory, and when to copy.

NumPy view vs copy: how to tell which an operation returns, and why it matters for aliasing bugs

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

What is the difference between a view and a copy in NumPy? How can you tell if an operation returns a view or a copy, and why is this distinction important for aliasing bugs? ```hint What an array stores An array is more than its numbers: it also has a shape, strides and a pointer into a data buffer. Ask which operations can be expressed by changing only that metadata. ``` ```hint Try it Write into the result of a slice and into the result of an integer-array index, then print the original array each time. ``` ### What a Strong Answer Covers - What a view and a copy are in terms of the data buffer and the array metadata - Which common operations return views, which return copies, and which depend on memory layout - Ways to check which one you have, and the limits of each check - How aliasing bugs arise and how to avoid them ### Follow-up Questions - Why does `a[[0, 2]] = 0` change `a` while `a[[0, 2]][0] = 0` does not? - When does `reshape` return a copy, and how do `ravel` and `flatten` differ? - A function slices its input array and modifies the slice. How do you protect the caller's data? - Why can keeping a small slice of a large array waste memory?

Overview: Asks how NumPy views differ from copies, how to tell which one an operation returns, and why the difference causes aliasing bugs. Tests buffer sharing, slicing versus fancy indexing, the base attribute and np.shares_memory, and when to copy.

PracHub logo
General
Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

What is the difference between a view and a copy in NumPy? How can you tell if an operation returns a view or a copy, and why is this distinction important for aliasing bugs?

What a Strong Answer Covers Guidance

  • What a view and a copy are in terms of the data buffer and the array metadata
  • Which common operations return views, which return copies, and which depend on memory layout
  • Ways to check which one you have, and the limits of each check
  • How aliasing bugs arise and how to avoid them

Follow-up Questions Guidance

  • Why does a[[0, 2]] = 0 change a while a[[0, 2]][0] = 0 does not?
  • When does reshape return a copy, and how do ravel and flatten differ?
  • A function slices its input array and modifies the slice. How do you protect the caller's data?
  • Why can keeping a small slice of a large array waste memory?