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
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
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.
d = {} will create a new instance for d but all other references will still point to the old contents. .clear() will reset the contents, but all references to the same instance will still be correct.
In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:
python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop
python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop