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?

  1. A.

    del(D) / del(D)

  2. B.

    D.del() / D.del()

  3. C.

    D.clear() / D.clear()

  4. 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:

  1. D = {'A': 1, 'B': 2}

  2. del D # D is no longer defined

  3. D = {'A':1}; D.clear() # D is {} (empty dict), not deleted

Explore the full course: Rssb Senior Computer Instructor