Copy vs View
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:
- Creates a copy and a view of the array
- Modifies the first element of each to 999
- 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
[1, 2, 3, 4, 5]
{'original': [999, 2, 3, 4, 5], 'copy_modified': False, 'view_modified': True}- Input:
arris a 1-D integer array of 5 elements, . Picture it as one block of memory. - The copy: a copy is a second, independent block with the same values, . Setting changes only that new block, so is still and the answer for
copy_modifiedisFalse. - The view: a view is a new array object that reads and writes the same block as . Setting writes into that shared memory, so afterwards and
view_modifiedisTrue. - Output:
originalreports 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 would wrongly make the copy look like it leaked. A one-element array such as ends as the same way.
Constraints
- Use .copy() for deep copy
- Use .view() for shallow view
- Array will have at least 1 element