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.

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:

Python set remove if exists

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 *

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