Python Set remove()

Python Set remove()

The remove() method removes the specified element from the set.

The syntax of the remove() method is:

set.remove(element)

remove() Parameters

The remove() method takes a single element as an argument and removes it from the set.


Return Value from remove()

The remove() removes the specified element from the set and updates the set. It doesn't return any value.

If the element passed to remove() doesn't exist, KeyError exception is thrown.


Example 1: Remove an Element From The Set

# language set
language = {'English', 'French', 'German'}

# removing 'German' from language
language.remove('German')

# Updated language set
print('Updated language set:', language)

Output

Updated language set: {'English', 'French'}

Example 2: Deleting Element That Doesn't Exist

# animal set
animal = {'cat', 'dog', 'rabbit', 'guinea pig'}

# Deleting 'fish' element
animal.remove('fish')

# Updated animal
print('Updated animal set:', animal)

Output

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
    animal.remove('fish')
KeyError: 'fish'

You can use the set discard() method if you do not want this error.

The discard() method removes the specified element from the set. However, if the element doesn't exist, the set remains unchanged; you will not get an error.