Difference between dict.clear() and assigning {} in Python

后端 未结 8 924
我在风中等你
我在风中等你 2020-11-28 19:57

In python, is there a difference between calling clear() and assigning {} to a dictionary? If yes, what is it? Example:

d = {\"stuff\":\"         


        
8条回答
  •  感情败类
    2020-11-28 20:25

    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
    

提交回复
热议问题