v9.1.1
Menu

Copy vs View

mediumPROMiscNumPy ConceptsNumpy

Problem Statement

Understand the difference between array copies and views in NumPy.

Background

  • arr.copy(): Creates a deep copy (independent array)
  • arr.view() or slicing: Creates a view (shares data with original)
  • Modifying a view affects the original array!

Your Task

Write a function test_copy_view(arr) that:

  1. Creates a copy and a view of the array
  2. Modifies the first element of each to 999
  3. Returns a dictionary with:
    • "original": Original array as list (after modifications)
    • "copy_modified": Whether modifying copy affected original (boolean)
    • "view_modified": Whether modifying view affected original (boolean)

Output Format

Return a dictionary with exactly these three keys.

Example

Input
[1, 2, 3, 4, 5]
Output
{'original': [999, 2, 3, 4, 5], 'copy_modified': False, 'view_modified': True}
Reasoning
  • Input: arr is a 1-D integer array of 5 elements, a=(1,2,3,4,5)a = (1, 2, 3, 4, 5). Picture it as one block of memory.
  • The copy: a copy is a second, independent block with the same values, c=(1,2,3,4,5)c = (1, 2, 3, 4, 5). Setting c0=999c_0 = 999 changes only that new block, so a0a_0 is still 11 and the answer for copy_modified is False.
  • The view: a view is a new array object that reads and writes the same block as aa. Setting v0=999v_0 = 999 writes into that shared memory, so afterwards a0=999a_0 = 999 and view_modified is True.
  • Output: original reports the array after both experiments as a plain list, [999, 2, 3, 4, 5]. Only position 0 changed, and only because of the view; the other four values were never touched.
  • Notice that the copy experiment must be judged before the view writes 999, otherwise a0=999a_0 = 999 would wrongly make the copy look like it leaked. A one-element array such as (100)(100) ends as (999)(999) the same way.

Constraints

  • Use .copy() for deep copy
  • Use .view() for shallow view
  • Array will have at least 1 element

Learn this in

More from Numpy

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.