Menu Close

Python Set discard() Method

Python set discard

In this guide, we are going to learn all about set discard() pre-defined method using examples.
Python set discard() method is used to remove the specified item from the set. The discard function in python is only used with the set because it is a set method.


To understand this example you should have basic knowledge of the python set.

Python Set discard() Method

The discard function in Python is a set function that is used to remove the specified items from the set.

Syntax

The syntax of set discard function is:-

set.discard(item)

Parameter

Python set discard function accept one parameter.

  • item – Required. item to be delete from the set.

Python set discard() exmaple

Here we will use discard function in Python to remove specified item from the list.

Example 1:

my_set = { 'Python', 'Java', 'JavaScript', 'C++'}
print(my_set)
my_set.discard('Java')
print(my_set)

Output

{'Java', 'C++', 'Python', 'Javascript'}
{'C++', 'Python', 'Javascript'}

Example 2:

What happen, If you try to delete item that is not exist in set.

my_set = { 'Python', 'Java', 'JavaScript', 'C++'}
print(my_set)
my_set.discard('C')
print(my_set)

Output:

{'Python', 'Java', 'C++', 'Javascript'}
{'Python', 'Java', 'C++', 'Javascript'}

Note:- if the specified item does not exist in the set, the discard function will not raise any error.

Conclusion

In this tutorial, you have learned all about the python set discard() method to delete the specified items from the python set.
If the specified item does not exist in the set, the discard function will not raise any error.

I hope this article will help you. If you like this article, please share it with your friends who want to learn Python programming from scratch.

Other set methods

For More Information:- Click Here

Python Set copy() Method
Python Set intersection() Method

Related Posts