Python: dictionary.clear vs Set Dictionary to Empty
In Python, there are 2 ways to clear a dictionary:
- Set to a empty dict:
xdict = {}
- Use the clear method:
xdict.clear()
What is the difference?
- Setting to an empty dict changes the value of the variable.
- Using
.clear()
does not change the value of the variable.
# python 3 # 2 ways to clear dictionary and their difference xdict = {'a':3, 'b':4} bb = xdict # set to a new empty dict xdict = {} # bb remains print(bb) # {'a': 3, 'b': 4} # HHHH------------------------------ xdict = {'a':3, 'b':4} bb = xdict # clear dict entries xdict.clear() # bb is now also empty print(bb) # {}