Skip to main content

Python Set discard() Function

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

Syntax

my_set.discard(item)

discard() Parameters

Python Set discard() function parameters:

ParameterConditionDescription
itemRequiredAn item you want to remove from the set

discard() Return Value

Python Set discard() function does not return any value; it modifies the set in-place.

Examples

Example 1: Discard an existing Element

my_set = {1, 2, 3, 4, 5}
my_set.discard(3)
print(my_set) # Output: {1, 2, 4, 5}

output

{1, 2, 4, 5}

Example 2: Discard Element that Does Not Exist in the Set

If specified item does not exist in a set, discard() method does nothing.

my_set = {1, 2, 3, 4, 5}
my_set.discard(10)
print(my_set) # Output: {1, 2, 3, 4, 5}

output

{1, 2, 3, 4, 5}

discard() method vs remove() method

discard() and remove() methods work in the same way. The only difference is that the remove() method raises KeyError, if specified item does not exist in a set.

my_set = {'Tom', 'Ryan', 'David'}
my_set.remove('Anna') # raises KeyError: 'Anna'
print(my_set)

output

Traceback (most recent call last):
File "main.py", line 2, in <module>
my_set.remove('Anna')
KeyError: 'Anna'

While discard() method does nothing.

my_set = {'Tom', 'Ryan', 'David'}
my_set.discard('Anna') # nothing happens
print(my_set) # Output: {'David', 'Tom', 'Ryan'}

output

{'David', 'Tom', 'Ryan'}