Does dictionary’s clear() method delete all the item related objects from memory?

Python documentation on dicts states that del d[key] removes d[key] from the dictionary while d.clear() removes every key, so basically their behavior is the same.

On the memory issue, in Python when you “delete” you are basically removing a reference to an object. When an object is not referenced by any variable nor other object or becomes unreachable, it becomes garbage and can be removed from memory. Python has a garbage collector that from time to time it does this job of checking which objects are garbage and releases the memory allocated for them.
If the object you are deleting from the dictionary is referenced by other variable then it is still reachable, thus it is not garbage so it won’t be deleted. I leave you here some links if you are interested in reading about garbage collection in general and python’s garbage collection in particular.

Leave a Comment