Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Python - Set remove() Method



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.

Return Value

None.

Example:

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

The output of the above code will be:

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

Traceback (most recent call last):
  File "Main.py", line 7, in <module>
    MySet.remove('DEC') 
KeyError: 'DEC'

❮ Python Set Methods




5