Python Set discard() Method

Removes a specified item from the set

Usage

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

Syntax

set.discard(item)

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

Examples

Example: Remove ‘red’ from the set

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

If specified item doesn’t exist in a set, discard() method does nothing.

Example: Try to remove ‘yellow’ from the set

S = {'red', 'green', 'blue'}
S.discard('yellow')
print(S)    # {'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.

Example: Try to remove ‘yellow’ from the set

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

However, discard() method does nothing.