Comparison of two methods of clearing the dictionary in python
The clear mentioned here refers to clearing the dictionary contents in python, which is different from deleting the dictionary.
For example:
d={'name':1,'age':2}
There are two methods to clear the dictionary
Method 1:
d.clear()
Print out d The value is {}
Method 2:
d={}
The value of printed d is {}
The difference between the two:
>>> d={'name':1,'age':2 }
>>> x = d
>>> x
{'age': 2, 'name': 1}
>>> x = {}
>>>
>>> d{'age': 2, 'name': 1}>>>You can see that when using x={}, what is cleared is the value of x itself, that is, the value of x to d The reference is changed, but the value of d is not changed>>> d={'namge':1,'age':2}>>> x = d>>> x{'namge' : 1, 'age': 2}>>> d{'namge': 1, 'age': 2}>>> x.clear()>>> x{} >>> d{}>>>When X=clear(), the value in the reference is cleared. When x=clear() is used, the value of d also changes, and when using The value of D does not change when x={}.