Python Set – discard() Method

It is a method in python set that removes the specified element from the current set. If it doesn’t exist then it doesn’t throws any Exception (no modification or error). It doesn’t return any value and modifies the given set. It takes a single parameter.

Syntax:
set.add(iterable_element)

Also Read: Python Set – remove() Method

Example 1:

# Python code to understand discard() method in set
# www.codewindow.in

s = {"amazing", "code", "best"}
s.discard("code")
print(s)

Output:

{'amazing', 'best'}

Explanation:
Here the element “code” has been removed from the parent set (s).

Example 2:

# Python code to understand discard() method in set
# www.codewindow.in

s = {5, 8, 4, 1, 5, 9}
s.discard(5)
print(s)

Output:

{1, 4, 8, 9}

Explanation:
Here the element “5” has been removed from the parent set (s).
Note: Set doesn’t allow duplicate element.

Example 3:

# Python code to understand discard() method in set
# www.codewindow.in

s = {5, 8, 4, 1, 5, 9}
s.discard(6)
print(s)

Output:

{1, 4, 5, 8, 9}

Explanation:
Here since the element is not present on the set it does nothing to the set.


Follow Us

You Missed

Also Checkout