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.
Parameters:
The clear() method take O(n) time.
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.
Python3
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.
Python3
text1 = { 1 : "geeks", 2 : " for "}
text2 = text1
text1.clear()
print ( 'After removing items using clear()' )
print ( 'text1 =' , text1)
print ( 'text2 =' , text2)
text1 = { 1 : "one", 2 : "two"}
text2 = text1
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'}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
13 Dec, 2022
Like Article
Save Article