Bird
0
0

You want to change elements in a slice of a NumPy array without modifying the original array. Which code snippet correctly achieves this?

hard📝 Application Q8 of 15
NumPy - Indexing and Slicing
You want to change elements in a slice of a NumPy array without modifying the original array. Which code snippet correctly achieves this?
import numpy as np
arr = np.array([7, 14, 21, 28, 35])
slice_arr = arr[1:4]
# What should you do next?
AModify <code>arr</code> directly without slicing
BAssign <code>slice_arr = arr[1:4]</code> and modify directly
CUse <code>slice_arr = list(arr[1:4])</code> and modify the list
DCreate a copy of the slice using <code>slice_arr = arr[1:4].copy()</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand views vs copies

    Slicing returns a view; modifying it changes the original.
  2. Step 2: Use .copy() to avoid affecting original

    Creating a copy ensures changes do not propagate.
  3. Final Answer:

    Create a copy of the slice using slice_arr = arr[1:4].copy() -> Option D
  4. Quick Check:

    Copy prevents original array modification [OK]
Quick Trick: Use .copy() to avoid modifying original array [OK]
Common Mistakes:
  • Modifying slice without copying
  • Using list conversion which loses NumPy features
  • Assuming direct modification is safe

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes