The Python Set discard() method is used to remove a specified element from a set. Unlike the remove() method, if the element is not found in the set, no error is raised and the set remains unchanged. When you are unsure whether the element exists in the set, this method is a safer alternative to the remove() method .
SyntaxFollowing is the syntax and parameters of Python Set discard() method −
set.discard(element)Parameter
The following is the parameter of the discard() method −
This method returns new set containing elements common to all specified sets.
Example 1Following is the basic example of python set discard() method. Here in this example we are creating a set with specified elements and removing the element 3 from the set using the discard() method −
# Define a set my_set = {1, 2, 3, 4, 5} # Remove element 3 from the set my_set.discard(3) print(my_set)Output
{1, 2, 4, 5}Example 2
When we try to remove an element which is not in the set then no error will be raised. Here is the example which shows that as specified element 6 is not present in the set, so no error is raised −
# Define a set my_set = {1, 2, 4, 5} # Try to remove non-existing element 6 from the set my_set.discard(6) print(my_set)Output
{1, 2, 4, 5}Example 3
In this example the discard() method is used with conditional statements to safely remove elements from sets −
# Define a set my_set = {1, 2, 3, 4, 5} # Safely remove element if present if 3 in my_set: my_set.discard(3) print(my_set)Output
{1, 2, 4, 5}Example 4
The key difference between discard() and remove() methods is that discard() does not raise an error if the element is not found whereas, the remove() raises a KeyError. Here in this example we show the difference between the remove() method and the discard() method −
# Define a set my_set = {1, 2, 4, 5} # Try to remove non-existing element 3 using discard() my_set.discard(3) print(my_set) # Output: {1, 2, 4, 5} # Try to remove non-existing element 3 using remove() my_set.remove(3) # This raises a KeyError since 3 is not present in the setOutput
{1, 2, 4, 5} Traceback (most recent call last): File "\sample.py", line 10, in <module> my_set.remove(3) # This raises a KeyError since 3 is not present in the set ^^^^^^^^^^^^^^^^ KeyError: 3
python_set_methods.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4