d={}
creates a new dictionary.
d.clear()
clears the dictionary.
If you use d={}
, then anything pointing to d
will be pointing to the old d
. This may introduce a bug.
If you use d.clear()
, then anything pointing at d
will now point at the cleared dictionary, this may also introduce a bug, if that was not what you intended.
Also, I don't think d.clear()
will (in CPython) free up memory taken up by d
. For performance, CPython doesn't take the memory away from dictionaries when you delete elements, as the usual use for dictionaries is building a big dictionary, and maybe pruning out a few elements. Reassigning memory (and making sure the hash table stays consistent) would take too long in most use cases. Instead, it fills the dictionary with turds
(that's the technical term on the mailing list), which indicate that an element used to be there but since got deleted. I'm not entirely sure if d.clear()
does this though, but deleting all the keys one by one certainly does.