The set discard() method is different from the set remove() method because the remove() method will raise the error if the specified item does not exist, whereas the discard() method will not raise any error.
Python Set discard
Python set discard() is a built-in method that removes an element from the set only if the item is present in the set. If an element does not present in the set, then no error or exception is raised, and the original set is returned. The discard() method only removes an element in the Set.
Syntax
set.discard(element)
Arguments
It takes one argument called an element, which we want to remove from the set.
Return Value
The discard() method does not return any value; it just returns None.
See the following code example.
# app.py # creating a set of even numbers till 10 evens = {2, 4, 6, 8, 10} # Printing the set print("The set is: ", evens) # Now we will discard 8 from the set evens.discard(8) # Printing new set print("New set is: ", evens) # Asking user to enter the value # which to be discarded x = int(input("Enter number which you want to discard: ")) # discarding the value evens.discard(x) # printing the new set print("Now new set is: ", evens)
Output
The set is: {2, 4, 6, 8, 10} New set is: {2, 4, 6, 10} Enter number which you want to discard: 4 Now new set is: {2, 6, 10}
In this example, we have created a set of even numbers until 10. Then we discarded 8 from the set and saw what the result was.
Then we asked the user to give input on which number they wanted to discard, and then we called the discard() function and removed that element.
Please note that if the user enters any number not present in the set, it will do nothing.
Element is not present in Set.
Let’s take a scenawherehich the item is not present in the set, and we try to remove the item from the set using the discard() method.
# app.py def RemoveElement(setA): setA.discard(24) print(setA) setA = set([11, 21, 19, 46, 29, 18]) RemoveElement(setA)
Output
python3 app.py {11, 46, 18, 19, 21, 29}
From the output, it returns the original set and does not raise any exceptions. The order of the element is different, but the items are the same.
That’s it for this tutorial.