Python dictionary clear() - Remove all the elements from the dictionary

The clear() removes all the elements from a dictionary.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

d.clear()

print(d)  # {}

The cleared dictionary is empty and the id doesn't change.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}
print(id(d))  # 4340802368

d.clear()
print(id(d))  # 4340802368

If you want to remove one element, use pop() instead.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

d.pop('NV')

print(d)  # {'CA': 'California', 'TX': 'Texas'}

Assign an empty dictionary to the dictionary

If you assign an empty dictionary to the dictionary, the original dictionary is an empty but its id changes. An id represents the memory address in Python so the old and new dictionary are essentially different.

d = {'x': 1, 'y': 2}

print(id(d))  # 4354643008

d = {}

print(d)  # {}
print(id(d))  # 4354643072

Comments

Powered by Markdown

More