Python dictionary Method - clear()

h‮//:sptt‬www.theitroad.com

The clear() method is a built-in dictionary method in Python that removes all the items (key-value pairs) from a dictionary. The clear() method does not return anything, it just modifies the original dictionary in place.

Here's the syntax for the clear() method:

my_dict.clear()

Here's an example:

# create a dictionary
my_dict = {'apple': 2, 'banana': 3, 'cherry': 4}

# clear the dictionary
my_dict.clear()

# print the dictionary after clearing it
print(my_dict)

Output:

{}

In this example, we create a dictionary my_dict with three key-value pairs, and then call the clear() method to remove all the items from the dictionary. After calling clear(), the dictionary becomes empty, as shown by the empty curly braces in the output.

The clear() method is useful when you want to remove all the items from a dictionary without having to delete and recreate the dictionary object. It can be used, for example, when you need to reuse a dictionary for a different purpose or when you want to free up memory used by a large dictionary.