Consider the following code snippet using NumPy arrays. What will be the output of print(a)?
import numpy as np a = np.array([1, 2, 3, 4, 5]) b = a[1:4] b[0] = 100 print(a)
Remember that slicing a NumPy array returns a view, not a copy.
Slicing a NumPy array returns a view, so modifying b changes the original array a. Only the element at index 1 changes to 100.
What will be printed after running this code?
import numpy as np a = np.array([10, 20, 30]) b = np.copy(a) b[1] = 99 print(a)
np.copy() creates a new array independent of the original.
Using np.copy() creates a new array b that does not share data with a. Changing b does not affect a.
Given the following code, what is the shape of b?
import numpy as np a = np.arange(12).reshape(3,4) b = a[:, 1:3].copy() print(b.shape)
Check the slicing dimensions before copying.
The slice a[:, 1:3] selects all rows and columns 1 and 2, resulting in shape (3, 2). The copy does not change shape.
Examine the code below. Why does it raise an error?
import numpy as np a = np.array([1, 2, 3]) b = a[::2] b[2] = 10 print(a)
Check the length of the sliced array b.
The slice a[::2] returns elements at indices 0 and 2, so b has length 2. Trying to assign b[2] = 10 raises IndexError: assignment index out of range because index 2 is out of bounds for array of size 2.
You have a 2D NumPy array a. You want to create a new array b that you can change freely without changing a. Which code snippet achieves this?
Think about which method creates a deep copy.
a.copy() creates a new array with its own data. Changes to b do not affect a. Other options create views or shallow copies.