Bird
0
0

What is wrong with the following code if the goal is to create a copy of the slice?

medium📝 Debug Q6 of 15
NumPy - Indexing and Slicing
What is wrong with the following code if the goal is to create a copy of the slice?
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
slice_arr = arr[1:4]
slice_arr[0] = 100
print(arr)
AThe array cannot be sliced this way
BThe slice syntax is incorrect
CThe print statement is invalid
DThe slice is a view, so modifying it changes the original array
Step-by-Step Solution
Solution:
  1. Step 1: Understand slicing returns a view

    The slice slice_arr shares data with arr.
  2. Step 2: Identify why original array changes

    Modifying slice_arr changes arr because no copy was made.
  3. Final Answer:

    The slice is a view, so modifying it changes the original array -> Option D
  4. Quick Check:

    Slice is view, not copy = C [OK]
Quick Trick: Slicing alone does not copy; use .copy() to avoid changes [OK]
Common Mistakes:
  • Assuming slicing creates a copy
  • Thinking syntax is wrong
  • Believing print causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NumPy Quizzes