Python Set remove() Method

Removes a specified item from the set

Usage

The remove() method removes a specified item from the set.

If specified item is not present in the set, the method raises KeyError.

Syntax

set.remove(item)

Python set remove() method parameters
ParameterConditionDescription
itemRequiredAn item you want to remove from the set

Examples

Example: Remove ‘red’ from the set

S = {'red', 'green', 'blue'}
S.remove('red')
print(S)    # {'blue', 'green'}

remove() method raises KeyError, if specified item doesn’t exist in a set.

Example: Try to remove ‘yellow’ from the set

# KeyError: 'yellow'
S = {'red', 'green', 'blue'}
S.remove('yellow')
print(S)

remove() vs discard()

Both methods work exactly the same.

The only difference is that the discard() method doesn’t raise any error if specified item doesn’t exist in a set.

Example: Try to remove ‘yellow’ from the set

S = {'red', 'green', 'blue'}
S.discard('yellow')
print(S)    # {'blue', 'green', 'red'}