The discard()
method in Python is a set method that removes a specific element from a set if it is present. If the element is not found in the set, the method does nothing and does not raise an error. It is different from the remove()
method, which raises an error if the element is not present in the set.
Parameter Values
Parameter | Description |
---|---|
value | The value to be removed from the set. If the value is not present in the set, discard() has no effect. |
Return Values
The discard()
method returns None
.
How to Use discard()
in Python
Example 1:
The discard()
method removes a specified element from the set if it is present.
my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set)
Example 2:
If the element is not present in the set, discard()
does nothing and does not raise an error.
my_set = {1, 2, 4, 5}
my_set.discard(3)
print(my_set)
Example 3:
discard()
is useful when you want to remove an element from a set without raising an error if the element is not in the set.
my_set = {1, 2, 3, 4, 5}
my_set.discard(6)
print(my_set)