Python Tutorial Python Advanced Python References Python Libraries

Python Set - discard() Method



The Python discard() method is used to delete specified element from the set. Unlike set remove() method, it does not raises any exception if specified element is not present in the set.

Syntax

set.discard(elem)

Parameters

elem Required. specify the element which need to be removed from the set.

Return Value

None.

Example:

In the example below, 'MAR' element is deleted from the set called MySet using discard() method. After that, the same method is used to delete 'DEC' element which is not present in the set and it does not raises any exception.

month = {'JAN', 'FEB', 'MAR', 'APR'}
#deletes 'MAR' from the set.
month.discard('MAR') 
print(month)

#throws no error when element is not in the set.
month.discard('DEC') 
print(month)

The output of the above code will be:

{'APR', 'JAN', 'FEB'}
{'APR', 'JAN', 'FEB'}

❮ Python Set Methods