thebench.bio #1 Ecosystem for the Bio-Tech Industry
All Python for Scientific Computing questions

Question 7 of 20 Fundamentals Concept

What is the difference between a view and a copy in NumPy?

Short answer

A view shares the original array's data buffer, so writing through it changes the original. A copy owns new memory. Basic slicing returns views, while indexing with a list, an integer array or a boolean mask returns a copy.

Why

NumPy can describe the same block of memory in a new way by changing only metadata such as shape, strides and dtype. That new description is a view. Slicing a plate-reader matrix with plate[0:8, 0:6] gives a view, so subtracting a blank from that slice in place also changes the full plate array.

Selecting wells with plate[[0, 2, 4]] or plate[plate > 1.5] is advanced indexing, which always returns a copy, so editing the result leaves the original untouched. You can check which one you hold: a view's base attribute points at the original array, while a copy's base is None, and np.shares_memory answers the question directly. Views matter for memory too.

Keeping a small slice of a huge array keeps the whole huge array alive, so the NumPy indexing guide recommends an explicit copy() in that case. The rule has edges. reshape returns a view when it can and a copy when the memory layout forbids it, and ravel behaves the same way, while flatten always copies. pandas follows different rules, and since pandas 3.0 Copy-on-Write means a subset behaves as a copy whenever you write to it.

A strong answer covers

  • View shares the data buffer, copy owns new memory
  • Basic slicing gives views, list, integer-array and boolean indexing give copies
  • Check with the base attribute or np.shares_memory
  • A small slice can keep a large array in memory
  • reshape and ravel copy only when the layout forces it

Common mistakes

  • Assuming every indexing operation copies, as it does for a Python list slice, and then mutating a slice in place
  • Expecting an in-place edit on a boolean-masked selection held in a new variable to update the source array