Python

clear method in set

Click for All Topics

clear method in set - Python

  • The clear method is used to remove all elements or items from the set.
  • It will delete all items and make the set empty.
  • When we call the clear method on a set it will iterate through the elements of the set and delete the elements one by one until the set is not empty.
  • The clear method doesn’t take any argument.
  • This method returns nothing.
  • When we call the clear method on an empty set it will not give any error.
  • The time complexity of the clear method is O(n) where n is the number of elements.

 

Syntax –

set_name.clear()

 

Example 1- let’s see the example

				
					my_set={9,99,999,9999,99999}
print("my_set before clear:",my_set)
my_set.clear()
print("my_set after clear:",my_set)

# Output -
# my_set before clear: {99999, 99, 999, 9, 9999}
# my_set after clear: set()
				
			
  • In the above example, first we create a set called my_set with elements(9,99,999,9999,99999).
  • After creating the set print the my_set on the output screen using the print function.
  • Then we call the clear method on my_set and remove all elements of the set.
  • Then print the empty set.

 

Example 2- trying to give an argument to the clear method

				
					s={'This', 'is', 'edSlash'}
print(s)
s.clear('is')

# Output -
# {'This', 'is', 'edSlash'}
# Traceback (most recent call last):
  # File "/home/main.py", line 3, in <module>
    # s.clear('is')
# TypeError: set.clear() takes no arguments (1 given)
				
			

In the above example, we can see that we can’t give any argument to the clear method.

Example 3- Let’s see the return value of clear

				
					s={'Sanskrit','Hindi','English','Urdu'}
print(s)
return_value=s.clear()
print(s)
print(return_value)

# Output -
# {'Sanskrit', 'Hindi', 'Urdu', 'English'}
# set()
# None
				
			

In the above example, we can see that the return value of the clear method is None.

 

Example 4- Run clear method on an empty set

				
					my_set=set()
print(my_set)
my_set.clear()
print(my_set)

# Output -
# set()
# set()
				
			

Example 5-

				
					my_list=[11,10,11,15,18,12,10]
my_set=set(my_list)
print('set before clear',my_set)
my_set.clear()
print('set after clear:',my_set)

# Output -
# set before clear {10, 11, 12, 15, 18}
# set after clear: set()