Python Dictionary clear()

The clear() method removes all items from the dictionary.

The syntax of clear() is:

dict.clear()

clear() Parameters

The clear() method doesn't take any parameters.


Return Value from clear()

The clear() method doesn't return any value (returns None).


Example 1: How clear() method works for dictionaries?

d = {1: "one", 2: "two"}

d.clear()
print('d =', d)

When you run the program, the output will be:

d = {}

You can also remove all elements from the dictionary by assigning empty dictionary {}.

However, there is a difference between calling clear() and assigning {} if there is another variable referencing the dictionary.

d = {1: "one", 2: "two"}
d1 = d
d.clear()
print('Removing items using clear()')
print('d =', d)
print('d1 =', d1)

d = {1: "one", 2: "two"}
d1 = d
d = {}
print('Removing items by assigning {}')
print('d =', d)
print('d1 =', d1)

When you run the program, the output will be:

Removing items using clear()
d = {}
d1 = {}
Removing items by assigning {}
d = {}
d1 = {1: 'one', 2: 'two'}