The clear()
method remove all elements from a dictionary, effectively making it an empty dictionary.
The syntax of clear()
is as shown below:
d.clear()
Where d
is the dictionary.
The clear()
method does not take any parameters. It also does not return any value.
my_dict = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three'
}
#remove all elements
my_dict.clear()
#the dictionary is now empty
print(my_dict)
In the above example we removed all elements from d
using the clear()
method.
Note that the clear()
method does not delete the dictionary, it simply removes all of its elements, turning it into an empty dict
. To entirely delete a dictionary from program's scope, you can use the del
statement as shown below:
my_dict = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three'
}
#delete the dictionary
del my_dict
#the dictionary does not exist in memory
print(my_dict)
In the above example, a NameError
is raised because the dictionary has been deleted from the program's namespace.