AppDividend
Latest Code Tutorials

Python Dictionary Clear Example | clear() Method Tutorial

0

Python Dictionary Clear Example | clear() Method Tutorial is today’s topic. If you are new to Python Dictionary, then check out this article. Dictionary is the collection which is unordered, changeable and indexed. Python Dictionary clear() method removes all items from the dictionary. It takes no parameter. The clear() method doesn’t return any value.

Python Dictionary Clear Example

The syntax of the clear() method is following.

dictionary.clear()

Let us see the example.

# app.py

appDict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
print(appDict)
appDict.clear()
print(appDict)

In the above example, we have created a Python Dictionary and then clear all its items. See the below output.

 

Python Dictionary Clear Example | clear() Method Tutorial

You can also remove all elements from the dictionary by assigning an empty dictionary {}.

# app.py

appDict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
print(appDict)
appDict = {}
print(appDict)

We have assigned the empty dictionary.

 

Python Dictionary Clear Example

Difference between assigning {} and clear() method?

However, there is a big difference between calling clear() and assigning {}, if there is another variable referencing to that dictionary.

When we assign {} to the dictionary, a new empty dictionary is created and attached to the reference. But when we do clear on the dictionary reference, the actual dictionary content is removed, so all references referring to the dictionary become empty.

Python clear Dictionary is one of the Dictionary function, used to clear or remove total items (key-value pairs) from the Dictionary.

Finally, Python Dictionary Clear Example | clear() Method Tutorial is over.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.