Explain the difference between a shallow copy and a deep copy in NumPy

Quick Overview

Asks how a shallow copy and a deep copy of a NumPy array differ, and which common operations share the original data buffer or allocate a new one. Tests understanding of views, the .base attribute, memory sharing checks, and the object-dtype edge case.

Explain the difference between a shallow copy and a deep copy in NumPy

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

Explain the difference between a shallow copy and a deep copy in NumPy. ```hint Follow the data buffer For each kind of copy, ask whether the new array gets its own block of memory or points at the original one. The `.base` attribute of the result tells you. ``` ### What a Strong Answer Covers - Whether the new array shares the original's data buffer, and what that means for an element written through either array - Which common operations return a view and which allocate an independent copy - How to check in code whether two arrays share memory - The `dtype=object` case, where copying the buffer still leaves the referenced Python objects shared ### Follow-up Questions - Does fancy indexing or boolean masking return a view or a copy, and why? - `reshape` and `ravel` sometimes return a view and sometimes a copy. When does each happen? - A function receives a slice of a 10 GB array and keeps it in a cache. What happens to memory, and how would you fix it? - When would you call `.copy()` defensively inside a function that takes an array argument?

Overview: Asks how a shallow copy and a deep copy of a NumPy array differ, and which common operations share the original data buffer or allocate a new one. Tests understanding of views, the .base attribute, memory sharing checks, and the object-dtype edge case.

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

Explain the difference between a shallow copy and a deep copy in NumPy.

What a Strong Answer Covers Guidance

  • Whether the new array shares the original's data buffer, and what that means for an element written through either array
  • Which common operations return a view and which allocate an independent copy
  • How to check in code whether two arrays share memory
  • The dtype=object case, where copying the buffer still leaves the referenced Python objects shared

Follow-up Questions Guidance

  • Does fancy indexing or boolean masking return a view or a copy, and why?
  • reshape and ravel sometimes return a view and sometimes a copy. When does each happen?
  • A function receives a slice of a 10 GB array and keeps it in a cache. What happens to memory, and how would you fix it?
  • When would you call .copy() defensively inside a function that takes an array argument?