python set discard method

Python set discard() method

The python set discard() method is the same as the python set remove() method. This is used to discard or remove the specified element from the set. But the difference is that, if the particular element is not present in the set then the discard method will not show an error.

set discard() method in Python

Python set discard() method Syntax:

set.discard(element)

Here, the element is that which you want to remove.

set discard() method examples in Python

Below are the different types of examples of the discard() method.

Example 1:

s = {2,3,4,5}
s.discard(4)
print(s)


Output :

{2, 3, 5}

Example 2:

s = {2,3,4,5}
s.discard('4')
print(s)


In the above example, the ‘4’ is a string type that doesn’t present in a set. It’s not showing an error like the python set remove() method.

Output :

{2, 3, 4, 5}

Example 3:

s = {2,3,4,5}
s.discard(10)
print(s)


Here, you try to remove element 10 which is not present in the set. But as per the python discard method property, it will not throw an error.

Output :

{2, 3, 4, 5}

Example 4:

s= set((1,2,3))
s.discard(2)
print(s)


In the above example, the python set was created with the help of the set() property.

Output :

{1,3}

Example 5:

s = {'1','e',4,'g'}
print(s.discard(12))


Output :

None

Here the output is None, and the return type of the python discard method is None.

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!