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

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

    In addition, sometimes the dict instance might be a subclass of dict (defaultdict for example). In that case, using clear is preferred, as we don't have to remember the exact type of the dict, and also avoid duplicate code (coupling the clearing line with the initialization line).

    x = defaultdict(list)
    x[1].append(2)
    ...
    x.clear() # instead of the longer x = defaultdict(list)
    
    0 讨论(0)
  • 2020-11-28 20:33

    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.

    0 讨论(0)
提交回复
热议问题