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

后端 未结 8 918
我在风中等你
我在风中等你 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:28

    In addition to @odano 's answer, it seems using d.clear() is faster if you would like to clear the dict for many times.

    import timeit
    
    p1 = ''' 
    d = {}
    for i in xrange(1000):
        d[i] = i * i
    for j in xrange(100):
        d = {}
        for i in xrange(1000):
            d[i] = i * i
    '''
    
    p2 = ''' 
    d = {}
    for i in xrange(1000):
        d[i] = i * i
    for j in xrange(100):
        d.clear()
        for i in xrange(1000):
            d[i] = i * i
    '''
    
    print timeit.timeit(p1, number=1000)
    print timeit.timeit(p2, number=1000)
    

    The result is:

    20.0367929935
    19.6444659233
    

提交回复
热议问题