Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python Set – remove() method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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}

My Personal Notes arrow_drop_up
Last Updated : 05 Nov, 2021
Like Article
Save Article
Similar Reads
Related Tutorials