Python

clear() method in dictionary

Click for All Topics

clear() method in dictionary - Python

  • This method is used to clear all items from a dictionary or remove all items from a dictionary.
  • The .clear() method doesn’t take any argument and doesn’t return anything.
  • The time complexity of this method is O(n) where n is the number of items in the dictionary.
  • When we call this method with an empty dictionary then it does not give any error.

Syntax –

dictionary.clear()

Parameters –

  • argument → doesn’t take any argument
  • return → None(doesn’t return anything)

Example –

				
					my_dict={'1':'a','2':'b','3':'c','4':'d'}
print("Original Dictionary:",my_dict)

my_dict.clear()
print("Original Dictionary after clear:",my_dict)

# Output -
# Original Dictionary: {'1': 'a', '2': 'b', '3': 'c', '4': 'd'}
# Original Dictionary after clear: {}
				
			
  • In the above example ,first we create a dictionary with some elements and store it in my_dict variable.
  • After creating a dictionary print the original dictionary on the output screen.
  • Then removes all item from the dictionary using the .clear() method.
  • Finally, print the original empty dictionary on the output screen.

Example – Clear an empty dictionary

				
					dct={}
print("Original Dictionary:",dct)

dct.clear()
print("Original Dictionary after clear:",dct)

# Output -
# Original Dictionary: {}
# Original Dictionary after clear: {}
				
			

Example –

				
					my_dict={'name':'xyz', 'roll no':1,'year':4}
print("Original Dictionary:",my_dict)

return_value=my_dict.clear()
print("Original Dictionary after clear:",my_dict)
print("Return Value of clear method:",return_value)

# Output -
# Original Dictionary: {'name': 'xyz', 'roll no': 1, 'year': 4}
# Original Dictionary after clear: {}
# Return Value of clear method: None