Python Dictionary clear() Method

Removes all items from the dictionary

Usage

Use clear() method to remove all items from the dictionary.

The method does not return anything; it modifies the dictionary in place.

Syntax

dictionary.clear()

Example

Example: Clear the dictionary

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

clear() vs Assigning Empty Dictionary

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

For example,

Example:

old_Dict = {'name': 'Bob', 'age': 25}
new_Dict = old_Dict
old_Dict = {}
print(old_Dict)     # {}
print(new_Dict)     # {'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.

Example:

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