python set remove() function

Python set remove() method

The set remove() method in Python removes the specified element from the set. And if the specified element is not present in the set, it will show an error.

set remove() method in Python

Python set remove() syntax :

set.remove(element)

Here, the element is that which you want to remove.

set remove() method examples in Python

Below are the different types of examples of the remove() method.

Example 1:

s = {2,3,4,5}
s.remove(4)
print(s)


Output :

{2, 3, 5}

Example 2:

s = {2,3,4,5}
s.remove(10)
print(s)


Output :

Traceback (most recent call last):
 File "E:\Python files\kmtomile.py", line 30, in <module>
   s.remove(10)
KeyError: 10

Example 3:

s = {2,3,4,5}
s.remove("2")
print(s)


Output :

Traceback (most recent call last):
   s.remove("2")
KeyError: '2'

As you can see, here you remove the element “2” of string type, but in the specified set there is a 2 of integer type. Therefore, you got an error.

Example 4:

s= set((1,2,3))
s.remove(2)
print(s)


Output :

{1,3}

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!