Open In App

Python Set – remove() method

Improve
Improve
Like Article
Like
Save
Share
Report

Python remove() Function is a built-in method to remove elements from the set. remove() method takes exactly one argument.

Syntax

set.remove(element)

If the element passed to the remove() is present in the set then the element will be removed from the set. If the element passed to the remove() is not present in the set then KeyError Exception will be raised. The remove() method does not return any value.

Example 1:

Python3




numbers = {1,2,3,4,5,6,7,8,9}
print(numbers)
  
# Deleting 5 from the set
numbers.remove(5)
  
# printing the resultant set
print(numbers)


Output

{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 6, 7, 8, 9}

Example 2:

Python3




numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  
print(numbers)
  
# passing an element that is not in set
# this will throw an KeyError exception
try:
    numbers.remove(13)
except Exception as e:
    print("KeyError Exception raised")
    print(e, "is not present in the set")
  
# printing the resultant set
print("\nresultant set : ", numbers)


Output

{1, 2, 3, 4, 5, 6, 7, 8, 9}
KeyError Exception raised
13 is not present in the set

resultant set :  {1, 2, 3, 4, 5, 6, 7, 8, 9}


Last Updated : 05 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads