Introduction
Garbage collection helps clean up memory by removing data no longer needed. Array references let you share or copy data without extra memory use.
import numpy as np # Create an array original_array = np.array([1, 2, 3]) # Reference assignment (no new array created) reference_array = original_array # Copy array (new array created) copied_array = original_array.copy()
import numpy as np # Empty array reference empty_array = np.array([]) reference_empty = empty_array # One element array reference one_element_array = np.array([10]) reference_one_element = one_element_array # Changing reference affects original reference_one_element[0] = 20
import numpy as np # Copying array original_array = np.array([5, 6, 7]) copied_array = original_array.copy() copied_array[0] = 100
import numpy as np # Reference assignment array_a = np.array([1, 2, 3]) array_b = array_a array_b[1] = 99
import numpy as np # Create original array original_array = np.array([10, 20, 30]) print("Original array before changes:", original_array) # Create reference to original array reference_array = original_array # Create copy of original array copied_array = original_array.copy() # Change reference array reference_array[0] = 100 print("Original array after changing reference:", original_array) # Change copied array copied_array[1] = 200 print("Copied array after change:", copied_array) print("Original array after changing copy:", original_array)
.copy()?.copy() does not create a new array but a reference to the same data.a?.copy() method creates a new independent array with its own data.b = a shares data; copy(a) is invalid without import; slicing a[:] creates a view, not a full copy.import numpy as np x = np.array([1, 2, 3]) y = x y[0] = 10 print(x)
y is assigned to x, so both refer to the same array.y[0] to 10 changes the shared array, so x[0] is also 10.import numpy as np x = np.array([1, 2, 3]) y = x[:] y[0] = 5 print(x)
y shares data with x.y[0] to 5 modifies the shared data, so x[0] also becomes 5.a used in multiple variables. You want to free memory used by a when no longer needed. Which statement is TRUE about garbage collection in this context?a allows Python to free its memory automatically. -> Option BPass the test and this pattern moves unknown