Open In App

Python | remove() and discard() in Sets

In this article, we will see how to remove an element in a set, using the discard() and remove() method. We will also learn the difference between the two methods, although they produce the same results.

Example



Input: set = ([10, 20, 26, 41, 54, 20])
Output: {41, 10, 26, 54}
Input: set = (["ram", "aakash", "kaushik", "anand", "prashant"])
Output: {'ram', 'prashant', 'kaushik', 'anand'}

Python Set discard() method

The built-in method, discard() in Python, removes the element from the set only if the element is present in the set. If the element is absent in the set, then no error or exception is raised and the original set is printed.

Python Set discard(): The element is present

In this example, the element that we wanted to remove is present inside the set and we remove that element with the help of the discard() method.






def Remove(sets):
    sets.discard(20)
    print (sets)
      
# Driver Code
sets = set([10, 20, 26, 41, 54, 20])
Remove(sets)

Output:

{41, 10, 26, 54}

Python discard() in the Absence of the Element

In this example, the element that we wanted to remove is not present inside the set and when we try to remove that element from the set then nothing is removed and no exception is thrown.




def Remove(sets):
    sets.discard(21)
    print (sets)
      
# Driver Code
sets = set([10, 20, 26, 41, 54, 20])
Remove(sets)

Output:

{41, 10, 26, 20, 54}

Python remove() Method in Set

The built-in method, remove() in Python, removes the element from the set only if the element is present in the set, just as the discard() method does but If the element is not present in the set, then an error or exception is raised.

Python Set remove(): The Element is Present

In this example, the element that we wanted to remove is present inside the set and we remove that element with the help of remove() method.




def Remove(sets):
    sets.remove("aakash")
    print (sets)
      
# Driver Code
sets = set(["ram", "aakash", "kaushik", "anand", "prashant"])
Remove(sets)

Output:

{'ram', 'anand', 'prashant', 'kaushik'}

Python remove(): The Element is not Present

In this example, the element that we wanted to remove is not present inside the set and when we try to remove that element from the set then nothing is removed and an exception is thrown.




def Remove(sets):
    sets.remove("gaurav")
    print (sets)
      
# Driver Code
sets = set(["ram", "aakash", "kaushik", "anand", "prashant"])
Remove(sets)

Output:

No Output

Error

Traceback (most recent call last):
  File "/home/bf95b32da22ada77d72062a73d3e0980.py", line 9, in 
    Remove(sets)
  File "/home/bf95b32da22ada77d72062a73d3e0980.py", line 4, in Remove
    sets.remove("gaurav")
KeyError: 'gaurav'

Article Tags :