.discard()
Anonymous contributor
Anonymous contributor1 total contribution
Anonymous contributor
Published May 15, 2024
Contribute to Docs
In Python, the .discard()
method removes a specified element from a set. If the element is not found, it takes no action and does not raise an error either.
Syntax
set.discard(value)
set
: Refers to the set from which the specified element is to be removed.value
: Denotes the element to be removed from the set.
Example
The below example shows the usage of the .discard()
method:
coffee_set = {'espresso', 'flat_white', 'cappuccino', 'filter'}print(coffee_set)# Removing 'espresso' from the setcoffee_set.discard('espresso')print(coffee_set)# Removing 'latte' from the setcoffee_set.discard('latte')print(coffee_set)
The above code produces the following output:
{'espresso', 'flat_white', 'cappuccino', 'filter'}{'flat_white', 'cappuccino', 'filter'}{'flat_white', 'cappuccino', 'filter'}
In the above example, the code continues to get executed without any errors despite the attempt to remove the element latte
, which doesn’t even exist in the set.
Codebyte Example
Here is a codebyte example demonstrating the use of the .discard()
method:
All contributors
- Anonymous contributorAnonymous contributor1 total contribution
- Anonymous contributor
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.