Python .discard()
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 contributor
Contribute to Docs
- 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.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours