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)
| Parameter | Condition | Description |
| item | Required | An item you want to remove from the set |
Examples
# Remove 'red' from the set
S = {'red', 'green', 'blue'}
S.remove('red')
print(S)
# Prints {'blue', 'green'}remove() method raises KeyError, if specified item doesn’t exist in a set.
S = {'red', 'green', 'blue'}
S.remove('yellow')
print(S)
# Triggers KeyError: 'yellow'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.
S = {'red', 'green', 'blue'}
S.discard('yellow')
print(S)
# Prints {'blue', 'green', 'red'}