0
0
NumPydata~10 mins

Garbage collection and array references in NumPy - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a NumPy array named 'arr' with values from 1 to 5.

NumPy
import numpy as np
arr = np.array([1])
Drag options to blanks, or click blank then click option'
A(1, 2, 3, 4, 5)
B[1, 2, 3, 4, 5]
Crange(1, 6)
D{1, 2, 3, 4, 5}
Attempts:
3 left
💡 Hint
Common Mistakes
Using a tuple instead of a list.
Using a set which is unordered.
Using range object directly without converting to list.
2fill in blank
medium

Complete the code to create a new variable 'ref' that references the same NumPy array as 'arr'.

NumPy
ref = [1]
Drag options to blanks, or click blank then click option'
Aarr
Barr.view()
Carr.copy()
Dnp.array(arr)
Attempts:
3 left
💡 Hint
Common Mistakes
Using copy() which creates a new array.
Using view() which creates a shallow copy.
Creating a new array with np.array() which duplicates data.
3fill in blank
hard

Fix the error in the code to delete the original array and check if 'ref' still exists.

NumPy
import gc
arr = np.array([1, 2, 3])
ref = arr
[1]  # Delete arr
print(ref)
Drag options to blanks, or click blank then click option'
Aarr = None
Barr.clear()
Cgc.collect()
Ddel arr
Attempts:
3 left
💡 Hint
Common Mistakes
Using arr.clear() which is invalid for NumPy arrays.
Calling gc.collect() without deleting references first.
Setting arr to None but not deleting the name.
4fill in blank
hard

Fill both blanks to create a copy of 'arr' and then delete the original reference.

NumPy
copy_arr = arr[1]()
del [2]
Drag options to blanks, or click blank then click option'
Acopy
Barr
Cref
Dview
Attempts:
3 left
💡 Hint
Common Mistakes
Using view() instead of copy() which creates a shallow copy.
Deleting the wrong variable name.
Not deleting any variable.
5fill in blank
hard

Fill all three blanks to create a view of 'arr', modify it, and then check if 'arr' changed.

NumPy
view_arr = arr[1]()
view_arr[0] = [2]
print(arr[0] == [3])
Drag options to blanks, or click blank then click option'
Aview
B10
Dcopy
Attempts:
3 left
💡 Hint
Common Mistakes
Using copy() which does not affect the original array.
Setting the wrong value in the view.
Comparing to a wrong value in the print statement.