Removes a specified item from the set
Usage
The discard()
method removes a specified item from the set.
Syntax
set.discard(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.discard('red')
print(S)
# Prints {'blue', 'green'}
If specified item doesn’t exist in a set, discard()
method does nothing.
S = {'red', 'green', 'blue'}
S.discard('yellow')
print(S)
# Prints {'blue', 'green', 'red'}
discard() vs remove()
Both methods work exactly the same. The only difference is that, the 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'
However, discard()
method does nothing.