Python Set remove()

In this tutorial, we will learn about the Python Set remove() method with the help of examples.

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

Example

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

# remove English from the set
languages.remove('English')


print(languages)

# Output: {'Python', 'Java'}

1. Syntax of Set remove()

The syntax of the remove() method is:

set.remove(element)

2. remove() Parameters

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

3. 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.

4. 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'}

5. 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.