Python Set remove() Method

Python Set remove() is a built-in method that “removes the element 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 absent in the set, the KeyError exception is thrown.


evens = {2, 4, 6, 8, 10}

print("The set is: ", evens)


print("New set is: ", evens)

x = int(input("Enter number which you want to remove: "))


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 a set of even numbers until 10. Then we removed 6 from the set and saw what the result was.

Then we asked the user to give input on which number they wanted to discard, and then we called the 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 that doesn’t exist, an error is raised. Let’s take the example to see this remove() method behavior.

Leave a Comment

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