How does set remove() work in Python?

Python’s built-in remove() method is used to remove a specific item from a set.

It is important to note that this method differs from the discard() method, which does the same thing. However, unlike discard(), remove() will raise an error if the specified item does not exist in the set that calls the method.

Syntax

set.remove(value)

Parameters and return value

This method requires a value that will be removed, from the very set that calls the method to be passed as a parameter.

The return value of remove() is None.

Example #1

x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
x.remove('Cats')
print(x)

Example #2

#Passing a value as a parameter which doesn't exist
#in the set that is calling the method
x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
x.remove('Tigers')
print(x)

Free Resources