Python Set discard()

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

In this tutorial, we will learn the syntax of set.discard() method and go through examples covering different scenarios for the arguments that we pass to discard() method.

Syntax

The syntax of set.discard() is

set.discard(e)

where

ParameterDescription
eAn element to remove from the set.

If the specified element is not present in the set, the set remains unchanged and no error is raised.

ADVERTISEMENT

Examples

1. Discard the element (element present in the set)

In the following program, we will remove the element e from the set x.

Python Program

x = {'apple', 'banana', 'cherry'}
e = 'banana'
x.discard(e)
print(x)
Try Online

Program Output

{'apple', 'cherry'}

2. Discard the element (element is not present in the set)

In the following program, we will remove the element e from the set x. We take elements in set x such that the element e is not present in the set.

Python Program

x = {'apple', 'banana', 'cherry'}
e = 'mango'
x.discard(e)
print(x)
Try Online

Program Output

{'banana', 'cherry', 'apple'}

Conclusion

In this Python Tutorial, we learned about Python set method discard(). We have gone through the syntax of discard() method, and its usage with example programs.