Python: dictionary.clear vs Set Dictionary to Empty

By Xah Lee. Date: . Last updated: .

In Python, there are 2 ways to clear a dictionary:

What is the difference?

# 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)
# {}