Python Set discard()

Python Set discard() method

Python Set discard() method removes a specified element from the set.

In this tutorial, you will learn the syntax of Set discard() method, and how to use discard() method to remove one or more specified elements from a Set in Python.

Syntax of Set discard()

The syntax to call discard() method on a set is



Set discard() method takes one parameter.

Any valid Python object.
This object is removed from the set.

Return value

discard() method returns None.

Please note that the discard() method modifies the original set.

Difference between Set discard() and Set remove()

The difference between set discard() and set remove() methods is that, discard() method does not raise an exception when the specified element is not present in the Set, whereas remove() method raises an exception if the specified element is not present in the Set.


1. Removing element ‘c’ from the Set in Python

In this example, we take a set of elements in set_1. We have to remove the element 'c' from the set.

Call discard() method on the set set_1 and pass the element 'c' as argument to the method.

Python Program

set_1 = {'a', 'b', 'c', 'd'}

# Remove element from set

Run Code Copy


{'a', 'd', 'b'}

The element that is passed to the discard() method has been removed from the set.

2. Removing element from Set, where the element is not present in the Set

If you try removing an element that is not present in set, the original set is unchanged and no error is thrown.

In this example, we shall take a set, and try removing an element that is not present in the set.

Python Program

#initialize sets
set_1 = {'a', 'b', 'c', 'd'}

#remove element from set

Run Code Copy


{'a', 'd', 'b', 'c'}


In this Python Set Tutorial, we learned how to user discard() method to remove an element from the set.

Code copied to clipboard successfully 👍