Skip to content

Python set discard vs remove

  • by

Python set methods discard() and remove() are used to remove the specified item from the set. The difference between set discard and remove is the remove() method will raise an error if the specified item does not exist, and the discard() method will not.

The .remove() is the general case that gives the developer control over the exception and .discard() is just a special use case where the developer does not need to catch that execration.

You can use the discard method if you do not want to catch the ValueError due to something else with try-except blocks

Python sets discard vs remove

Simple example code.

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

s.discard('Bob')

# Bob value already discard
print(s.discard('Bob'))
print(s)

# trying to remove Bob
s.remove('Bob')

Output:

Python set discard vs remove
MethodDescriptionError Handling
discard()Removes a specified element if present.No error if element not present.
remove()Removes a specified element if present.Raises KeyError if not present.

Do comment if you have any doubts or suggestions on this Python method comparison 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 *