Python Set discard() Function
discard() is a built-in method to remove elements from the set. The discard() method takes exactly one argument. This method does not return any value.
Syntax:
set.discard(element)
If the element passed to the discard() is present in the set then the element will be removed from the set. Even If the element passed to the discard() method is not present in the set No Exception will be raised.
Example 1: Discard an element from the set
Python3
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9} print(numbers) # Deleting 5 from the setnumbers.discard(5) # printing the resultant setprint(numbers) |
Output:
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 6, 7, 8, 9}
Example 2: Discard an element from the set
Python3
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9} print(numbers) # passing an element that is not in setnumbers.discard(13)# this will not throw any errors but set remains # same as before # printing the resultant setprint("\nresultant set : ", numbers) |
Output:
{1, 2, 3, 4, 5, 6, 7, 8, 9}
resultant set : {1, 2, 3, 4, 5, 6, 7, 8, 9}
Example 3: Discard an element from the set
Python3
myset = {'a', 1, "geek", 2, 'b', 'abc', "geeksforgeeks", 8} print(myset) # Deleting a from the setmyset.discard("geek") # printing the resultant setprint(myset) |
Output:
{1, 2, ‘b’, ‘a’, 8, ‘geeksforgeeks’, ‘abc’, ‘geek’}
{1, 2, ‘b’, ‘a’, 8, ‘geeksforgeeks’, ‘abc’}
Example 4: Discard an element from the set
Python3
myset = {'a', 1, "geek", 2, 'b', 'abc', "geeksforgeeks", 8} print(myset) # trying to Delete geeksfrom the set which is not theremyset.discard("geeks") # printing the resultant setprint(myset) |
Output:
{1, 2, ‘b’, ‘a’, 8, ‘geeksforgeeks’, ‘abc’, ‘geek’}
{1, 2, ‘b’, ‘a’, 8, ‘geeksforgeeks’, ‘abc’, ‘geek’}

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.


Please Login to comment...