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

后端 未结 8 916
我在风中等你
我在风中等你 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)
    

提交回复
热议问题