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.
set.discard('element')
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'}
s.discard('Bob')
print(s.discard('Bob'))
print(s)
Output:
Another example:
my_set = {1, 2, 3, 4, 5}
# Using remove() - Raises KeyError if the element is not present
try:
my_set.remove(3)
except KeyError:
print("Element not found in the set")
# Using discard() - Doesn't raise an error if the element is not present
my_set.discard(3)
print(my_set)
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.