Python - Set discard() Method


Advertisements

The Python set 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.

Example:

In the below example, '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)

Output

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

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

Sets Methods




Advertisements