If D is a Python dictionary as D={'A':1, 'B':2, 'C':3} Then, which of the…
2023
If D is a Python dictionary as D={'A':1, 'B':2, 'C':3} Then, which of the following command will remove the entire dictionary from the memory?
- A.
del(D) / del(D)
- B.
D.del() / D.del()
- C.
D.clear() / D.clear()
- D.
D.remove() / D.remove()
Attempted by 1627 students.
Show answer & explanation
Correct answer: A
Answer: Use del D (or del(D)) to remove the dictionary from the namespace.
Key points:
del D removes the name D from the current namespace. After this, D is not defined in that scope.
If no other references to the dictionary object exist, it becomes eligible for garbage collection; otherwise the object remains until all references are gone.
D.clear() only removes all key-value pairs but leaves the variable D defined as an empty dictionary.
There is no D.del() or D.remove() method for dictionaries. To remove a specific key use D.pop(key) or del D[key]; to remove an arbitrary item use D.popitem().
Examples:
D = {'A': 1, 'B': 2}
del D # D is no longer defined
D = {'A':1}; D.clear() # D is {} (empty dict), not deleted