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(element)

Parameters

Set discard() method takes one parameter.

ParameterDescription
elementRequired
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.

Examples

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
set_1.discard('c')

print(set_1)
Run Code Copy

Output

{'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
set_1.discard('k')

print(set_1)
Run Code Copy

Output

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

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍