Python Set discard() Method

Python Set discard() method is used to remove the specified item from the set. This method differs from the remove() method because the remove() method raises an error if the specified item does not exist, while the discard() method doesn’t.




It takes one argument called an element, which we want to remove from the set.

Return Value

This method does not return any value; it just returns None.

Visual Representation

Visual Representation of How to Use Set discard() Method

Example 1: How to Use Set discard() Method

# creating a set of even numbers till 10
evens = {2, 4, 6, 8, 10}

# Printing the set
print("The set is: ", evens)

# Now we will discard 8 from the set

# Printing new set
print("New set is: ", evens)


The set is: {2, 4, 6, 8, 10}

New set is: {2, 4, 6, 10}

Example 2: Element is not present in Set

Let’s take a scenario in which the element is not present in the set, and we try to remove the item from the set using the discard() method.

def RemoveElement(setA):

setA = set([11, 21, 19, 46, 29, 18])


{11, 46, 18, 19, 21, 29}

From the output, it returns the original set and does not raise any exceptions. The order of the element is different, but the items are the same.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.