Last Updated : 25 Feb, 2025
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:
Python
d = {1: "geeks", 2: "for"}
# using clear() to remove all items
d.clear()
print(d)
Explanation: In this example, after calling clear()
, the dictionary d
becomes empty.
clear() syntaxNote: clear() method is safe to use and won't raise errors, even if the dictionary is already empty. It simply clears all items.
dict.clear()
Here, dict is the dictionary on which the clear() method is called.
Parameters:
Returns:
Example 1: clear() on an already empty dictionary.
Python
# creating an empty dictionary
d = {}
# Using clear() on the already empty dictionary
d.clear()
print(d)
Explanation: In this case, the dictionary was already empty, but calling clear() does not change its state.
Example 2: Clearing a dictionary after operations.
Python
# dictionary with some initial values
d = {'apple': 2, 'banana': 3, 'orange': 1}
# performing some operations
d['apple'] = 5
d.clear()
print(d)
Explanation: In this case, the dictionary d is updated before calling clear(). After calling the method, the dictionary becomes empty.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4