Python Set remove(): The Complete Guide

Python set remove() method searches for the given element in the set and removes it. The difference between discard() and remove() method is, in discard() method, if the element is not present in the set, it does not throw any exception, wherein remove() method if the element is not present in the set, it throws an exception.

Python Set remove()

Python Set remove() is a built-in function that is used to remove any specified element from a set. The remove() method removes the element that is present in the set.



Here the element is the argument that we want to remove from the set.

Return Value

The set remove() method does not return any value; it just returns None. But if the element is not present in the set, then the KeyError exception is thrown.


See the following programming example.


# creating a set of even numbers till 10
evens = {2, 4, 6, 8, 10}
# Printing the set
print("The set is: ", evens)

# Now we will discard 8 from the set

# Printing new set
print("New set is: ", evens)

# Asking user to enter the value
# which to be discarded
x = int(input("Enter number which you want to remove: "))
# discarding the value
# printing the new set
print("Now new set is: ", evens)


The set is:  {2, 4, 6, 8, 10}
New set is:  {2, 4, 8, 10}
Enter number which you want to remove: 16
Traceback (most recent call last):
  File "", line 16, in <module>
KeyError: 16

In this example, we have created the set of even numbers until 10. Then we have removed 6 from the set and see what the result is.

Then we have asked the user to give input on which number he/she wants to discard, and then we have called remove() function. But the user entered 16 as input, which is not present in the set, so the program threw a KeyError exception.

If you try to remove an element from the Set which doesn’t exist, then an error is raised. Let’s take the example to see this behavior of remove() method.

That’s it for this tutorial.

See also

Python set pop()

Python set issuperset()

Python set issubset()

Python set isdisjoint()

Python set intersection_update()

Python set intersection()

Python set discard()

Python set difference_update()

Python set difference()

Python set copy()

Python set clear()

Python set add()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.