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

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

    Mutating methods are always useful if the original object is not in scope:

    def fun(d):
        d.clear()
        d["b"] = 2
    
    d={"a": 2}
    fun(d)
    d          # {'b': 2}
    

    Re-assigning the dictionary would create a new object and wouldn't modify the original one.

提交回复
热议问题