In this tutorial, we’ll learn what Python dictionary clear method is and how to practically use it.
To better understand how Python dictionary clear method works, multiple Python code examples will be provided with detailed with step by step explanation.
After reading this post, you’ll have a detailed knowledge of how to properly use clear method.
What is Python Dictionary Clear Method?
This method is used to clear/remove all the items from Python dictionary, no matter how larger the number of items are.
Let’s first walk through its syntax, then we’ll practically implement it using multiple Python code examples for better understanding.
Syntax of Clear Method
dictionaryName.clear()
This method does not take any arguments. You can easily implement it like this.
Implementing Python Dictionary Clear Method (Multiple Examples)
Below examples with practically demonstrate how clear method works.
Example 1: Clear a Dictionary
dicItems={'Name':'Aneeq','age':26,'height':6} print(dicItems) // {'Name': 'Aneeq', 'age': 26, 'height': 6} dicItems.clear() // clear this dictionary print(dicItems) // {}
Output
{'Name':'Aneeq','age':26,'height': 6} // before applying clearn method {} // after applying clear methof
All the items of dictionary is deleted/removed which means the clear() method has done its job.
Example 2: clear() Method Returns None
dicItems={'Name':'Aneeq','age':26,'height':6} print(dicItems.clear())
Output
None
This clear() method just remove all the items from the existing dictionary, not returning anything. If you print the dictionary now then you will see that its empty. See below code:
dicItems={'Name':'Aneeq','age':26,'height':6} print(dicItems.clear()) // None print(dicItems) // {}
Output
None // clear method returns none {} // empty dictionary
This is how you can use Python dictionary clear method in your own code as well. Hope you’ve learned alot from this post.
Don’t hesitate to ask if you still have questions related to the implementation of Python dictionary clear method. I’ll be very glad to answer all your questions.
Conclusion
To conclude this post, now you have an in-depth practical understanding of how to properly use Python dictionary clear method. I’d be looking forward to receive your valuable feedback on this post. Thank you for reading it.