Python Dictionary clear()
The clear() method removes all items from the dictionary.
Syntax:
dict.clear()
Parameters:
The clear() method doesn't take any parameters.
Returns:
The clear() method doesn't return any value.
Examples:
Input : d = {1: "geeks", 2: "for"}
d.clear()
Output : d = {}
Error:
As we are not passing any parameters there is no chance for any error.
# Python program to demonstrate working of # dictionary clear() text = {1: "geeks", 2: "for"} text.clear() print('text =', text) |
Output:
text = {}
How is it different from assigning {} to a dictionary?
Please refer the below code to see the difference. When we assign {} to a dictionary, a new empty dictionary is created and assigned to the reference. But when we do clear on a dictionary reference, the actual dictionary content is removed, so all references referring to the dictionary become empty.
# Python code to demonstrate difference # clear and {}. text1 = {1: "geeks", 2: "for"} text2 = text1 # Using clear makes both text1 and text2 # empty. text1.clear() print('After removing items using clear()') print('text1 =', text1) print('text2 =', text2) text1 = {1: "one", 2: "two"} text2 = text1 # This makes only text1 empty. text1 = {} print('After removing items by assigning {}') print('text1 =', text1) print('text2 =', text2) |
Output:
After removing items using clear()
text1 = {}
text2 = {}
After removing items by assigning {}
text1 = {}
text2 = {1: 'one', 2: 'two'}
Recommended Posts:
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Convert string dictionary to dictionary
- set clear() in python
- How to clear screen in python?
- Different ways to clear a list in Python
- Python Dictionary
- Python | Get the first key in dictionary
- Python | Get key from value in Dictionary
- Few mistakes when using Python dictionary
- Python | Check if key has Non-None value in dictionary
- Python | Key index in Dictionary
- Python | Get key with maximum value in Dictionary
- Python | Add new keys to a dictionary
- Python | Get first K items in dictionary
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



