In Python, sets are collections of unique elements. Sometimes, you need to remove elements from a set. Python provides two methods for this: discard() and remove(). Both methods delete elements, but they behave differently when the element does not exist in the set.
discard() Method
discard() method removes an element if it exists in the set. If the element is not present, it does nothing, no error is raised.
Here, we are trying to discard an element which is present in the set.
s = {10, 20, 26, 41, 54}
s.discard(20)
print(s)
Output
{26, 54, 41, 10}
Explanation: discard(20) removes the element 20 from the set. Since the element exists, it is deleted successfully.
Here, we are trying to discard an element which is not present in the set.
s = {10, 20, 26, 41, 54}
s.discard(21)
print(s)
Output
{26, 20, 54, 41, 10}
Explanation: discard(21) does nothing because 21 is not in the set. No error is raised.
remove() Method
remove() method also deletes an element from the set if it exists, but unlike discard(), it raises an error if the element is not present.
Here, we are removing an element which is present in the set.
s = {"apple", "banana", "mango", "blueberry", "watermelon"}
s.remove("mango")
print(s)
Output
{'banana', 'apple', 'watermelon', 'blueberry'}
Explanation: remove("mango") successfully deletes the element "mango" from the set.
Here, we are removing an element which is not present in the set.
s = {"apple", "banana", "mango", "blueberry", "watermelon"}
s.remove("grapes")
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
KeyError: 'grapes'
Explanation: remove("grapes") raises a KeyError because "grapes" is not in the set.
discard() vs remove()
Below is the key difference of discard() and remove() in tabular form to sum it up:
| Method | When element exists | When element does NOT exist |
|---|---|---|
| discard() | Removes the element | Does nothing (no error) |
| remove() | Removes the element | Raises KeyError |