Open In App

Python Dictionary clear()

Last Updated : 25 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
{}

Explanation: In this example, after calling clear(), the dictionary d becomes empty.

Note: clear() method is safe to use and won't raise errors, even if the dictionary is already empty. It simply clears all items.

clear() syntax

dict.clear()

Here, dict is the dictionary on which the clear() method is called.

Parameters:

  • None: clear() method does not take any parameters.

Returns:

  • This method does not return anything. It modifies the dictionary in place, removing all items from it.

clear() examples

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)

Output
{}

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)

Output
{}

Explanation: In this case, the dictionary d is updated before calling clear(). After calling the method, the dictionary becomes empty.


Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy