Difference between dict.clear() and assigning {} in Python
In python, is there a difference between calling clear()
and assigning {}
to a dictionary? If yes, what is it?
Example:
d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
Solution 1:
If you have another variable also referring to the same dictionary, there is a big difference:
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}
This is because assigning d = {}
creates a new, empty dictionary and assigns it to the d
variable. This leaves d2
pointing at the old dictionary with items still in it. However, d.clear()
clears the same dictionary that d
and d2
both point at.
Solution 2:
d = {}
will create a new instance for d
but all other references will still point to the old contents.
d.clear()
will reset the contents, but all references to the same instance will still be correct.