Python Dictionary clear() Method

Removes all items from the dictionary

Usage

Use clear() method to remove all items from the dictionary. This method does not return anything; it modifies the dictionary in place.

Syntax

dictionary.clear()

Example

D = {'name': 'Bob', 'age': 25}
D.clear()
print(D)
# Prints {}

clear() vs Assigning Empty Dictionary

Assigning an empty dictionary D = {} is not same as D.clear(). For example,

old_Dict = {'name': 'Bob', 'age': 25}
new_Dict = old_Dict
old_Dict = {}
print(old_Dict)
# Prints {}
print(new_Dict)
# Prints {'age': 25, 'name': 'xx'}

old_Dict = {} does not empty the dictionary in-place, it just overwrites the variable with a different dictionary which happens to be empty. If anyone else like new_Dict had a reference to the original dictionary, that remains as-is.

On the contrary, clear() method empties the dictionary in-place. So, all the references are cleared as well.

old_Dict = {'name': 'Bob', 'age': 25}
new_Dict = old_Dict
old_Dict.clear()
print(old_Dict)
# Prints {}
print(new_Dict)
# Prints {}