Join our newsletter for the latest updates.
Python Set remove()

Python Set remove()

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

The syntax of the remove() method is:


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

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


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

Example 2: Deleting Element That Doesn't Exist

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

# Deleting 'fish' element

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


Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
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.