Thursday, October 23, 2025
HomeLanguagesPython Set – remove() method

Python Set – remove() method

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}
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS