Python Set remove()

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


languages = {'Python', 'Java', 'English'}

# remove English from the set languages.remove('English')
print(languages) # Output: {'Python', 'Java'}

Syntax of Set remove()

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 language.remove('German')
# 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 animal.remove('fish')
# 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.

Also Read:

Did you find this article helpful?