Difference between dict.clear() and assigning {} in Python
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping
--
Chapters
00:00 Difference Between Dict.Clear() And Assigning {} In Python
00:22 Accepted Answer Score 317
00:58 Answer 2 Score 33
01:20 Answer 3 Score 22
01:43 Answer 4 Score 9
01:58 Answer 5 Score 7
02:30 Thank you
--
Full question
https://stackoverflow.com/questions/3698...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping
--
Chapters
00:00 Difference Between Dict.Clear() And Assigning {} In Python
00:22 Accepted Answer Score 317
00:58 Answer 2 Score 33
01:20 Answer 3 Score 22
01:43 Answer 4 Score 9
01:58 Answer 5 Score 7
02:30 Thank you
--
Full question
https://stackoverflow.com/questions/3698...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary
#avk47
ACCEPTED ANSWER
Score 320
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.
ANSWER 2
Score 33
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.
ANSWER 3
Score 22
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
ANSWER 4
Score 9
As an illustration for the things already mentioned before:
>>> a = {1:2}
>>> id(a)
3073677212L
>>> a.clear()
>>> id(a)
3073677212L
>>> a = {}
>>> id(a)
3073675716L