Python Dictionary clear()
clear() method in Python is used to remove all items (key-value pairs) from a dictionary. After calling this method, the dictionary will become empty and its length will be 0. This method is part of the built-in dictionary operations in Python.
Example:
d = {1: "geeks", 2: "for"}
# using clear() to remove all items
d.clear()
print(d)
Output
{}
Explanation: In this example, after calling clear()
, the dictionary d
becomes empty.
Note: clear() method is safe to use and won't raise errors, even if the dictionary is already empty. It simply clears all items.
clear() syntax
dict.clear()
Here, dict is the dictionary on which the clear() method is called.
Parameters:
- None: clear() method does not take any parameters.
Returns:
- This method does not return anything. It modifies the dictionary in place, removing all items from it.
clear() examples
Example 1: clear() on an already empty dictionary.
# creating an empty dictionary
d = {}
# Using clear() on the already empty dictionary
d.clear()
print(d)
Output
{}
Explanation: In this case, the dictionary was already empty, but calling clear() does not change its state.
Example 2: Clearing a dictionary after operations.
# dictionary with some initial values
d = {'apple': 2, 'banana': 3, 'orange': 1}
# performing some operations
d['apple'] = 5
d.clear()
print(d)
Output
{}
Explanation: In this case, the dictionary d is updated before calling clear(). After calling the method, the dictionary becomes empty.