Skip to content

Python set remove if exists

  • by

Use the set discard() method to remove an element from a set if it exists, not the set remove() method. Both methods take an element to be removed as an argument and remove this element from the set.


Note: set.discard() doesn’t raise an error whereas set.remove() raises a KeyError if the element to be removed is not a member of the set.

Python set remove if exists

Simple example code.

s = {'Alice', 'Bob', 'Cloe'}




Python set remove if exists

Another example:

my_set = {1, 2, 3, 4, 5}

# Using remove() - Raises KeyError if the element is not present
except KeyError:
    print("Element not found in the set")

# Using discard() - Doesn't raise an error if the element is not present


In this example, the remove(3) will raise a KeyError because 3 is removed from the set. On the other hand, discard(3) will remove 3 if it exists in the set, but it won’t raise an error if the element is not found.

Do comment if you have any doubts or suggestions on this Python remove the topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *