Python - Set remove() Method


Advertisements

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

Syntax


set.remove(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 remove() method. After that, when the same method is used to delete 'DEC' element which is not present in the set, it raises an exception.

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

#throws an error as 'DEC' is not in the set.
MySet.remove('DEC') 
print(MySet)

Output

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

month.remove('DEC') KeyError: 'DEC'

Sets Methods




Advertisements