In Python, the clear()
method is used to remove all items from a dictionary. It is a built-in method available for dictionaries in Python.
clear()
method:
dictionary_name.clear()
dictionary_name
: This is the name of the dictionary from which you want to remove all items.The clear()
method does not return any value. It modifies the original dictionary in place by removing all key-value pairs, effectively making the dictionary empty.
Let's see an example of using the clear()
method:
# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Clear the dictionary (remove all items)
my_dict.clear()
print(my_dict) # Output: {}
As you can see, after calling the clear()
method on the dictionary, all key-value pairs are removed, leaving an empty dictionary.
The clear()
method can be useful when you want to reset or reinitialize a dictionary to an empty state. It's important to note that any references to the original dictionary will also reflect the changes made by the clear()
method.