Consider the following code snippet using NumPy arrays:
import numpy as np arr = np.array([1, 2, 3, 4]) view_arr = arr[1:3] view_arr[0] = 10 print(arr)
What will be the output of the print statement?
import numpy as np arr = np.array([1, 2, 3, 4]) view_arr = arr[1:3] view_arr[0] = 10 print(arr)
Think about whether view_arr is a copy or a view of arr.
The slice arr[1:3] creates a view, not a copy. Modifying view_arr[0] changes arr[1]. So the array becomes [1, 10, 3, 4].
What will be the output of this code?
import numpy as np arr = np.array([5, 6, 7, 8]) copy_arr = arr.copy() copy_arr[1] = 20 print(arr)
import numpy as np arr = np.array([5, 6, 7, 8]) copy_arr = arr.copy() copy_arr[1] = 20 print(arr)
Does modifying a copy affect the original array?
The copy() method creates a new array independent of the original. Changing copy_arr does not affect arr.
Given the following code, which statement correctly describes the reference count behavior?
import numpy as np arr = np.array([1, 2, 3]) ref1 = arr ref2 = arr ref1[0] = 10 print(arr)
import numpy as np arr = np.array([1, 2, 3]) ref1 = arr ref2 = arr ref1[0] = 10 print(arr)
Think about what happens when you assign arrays to new variables without copying.
Assigning arr to ref1 and ref2 creates references to the same array. Changing ref1[0] changes the original array, so arr and ref2 see the change.
Consider this code:
import numpy as np arr = np.array([1, 2, 3, 4]) new_arr = arr[::2] new_arr[0] = 100 print(arr)
Why does arr change even though slicing looks like it creates a new array?
import numpy as np arr = np.array([1, 2, 3, 4]) new_arr = arr[::2] new_arr[0] = 100 print(arr)
Check if slicing with steps returns a view or a copy.
In NumPy, slicing with steps returns a view, not a copy. So modifying new_arr changes the original arr.
Which statement best describes how Python's garbage collector handles NumPy arrays with multiple references?
Think about how reference counting works in Python.
Python uses reference counting for garbage collection. The memory for a NumPy array is freed only when no references remain.