Python set discard function is useful to discard or remove an item from the given set. The syntax this set discard function is:
set_Name.discard(element)
Python set discard Example 1
The set discard function is the same as remove function. This set function helps you to discard or remove an item from a given set. It is a very useful set function if you know the item you want to discard. The below code discards or remove 30 from a given set called discardSet
TIP: Please refer to the Python set article to understand everything about Sets in Python.
# Python set discard method discardSet = {10, 25, 30, 45, 50} print("\nOld Set Items = ", discardSet) # Python Discard Set Item discardSet.discard(30) print("After Discard Method - Set Items = ", discardSet)

How to discard set item Example 2
In this example, first, we declared a string set. Next, we used this set discard method on this string set. Here, discard function discard or remove the orange from the discard fruits set.
# Python set discard method discardFruitSet = {'apple', 'mango', 'cherry', 'kiwi', 'orange', 'banana'} print("\nOld Set Items = ", discardFruitSet) # Python Discard Set Item discardFruitSet.discard('orange') print("After Discard Method = ", discardFruitSet)

How to discard set item Example 3
As we said earlier, this Python set discard function is the same as the remove method. However, if we are discarding non-existing items, this function does not throw an error.
In this set discard example, we tried to remove Berry from the fruits set.
# Python set discard method discardFruitSet = {'apple', 'mango', 'cherry', 'kiwi', 'orange', 'banana'} print("\nOld Set Items = ", discardFruitSet) # Python Discard Set Item discardFruitSet.discard('orange') print("After Discard Method = ", discardFruitSet) # Python DIscard Non existing set item discardFruitSet.discard('Berry') print("After Discard Method = ", discardFruitSet)
