Set discard() Method in Python

Python Set discard() Method

The discard() method is used to remove a specific element from a set if it exists. If the element is not present in the set, the discard() method does nothing and does not raise an error.

Syntax of the discard() method:

your_set.discard(element)

Parameters:

  • your_set: The set from which you want to remove the element.
  • element: The element you want to remove from the set, if it exists.

Example:

# Creating a set of fruits
fruits = {'apple', 'banana', 'orange', 'grape'}

# Removing 'banana' from the set using discard()
fruits.discard('banana')

print(fruits)  # Output: {'apple', 'orange', 'grape'} (banana is removed from the set)

# Trying to remove an element that doesn't exist in the set
fruits.discard('watermelon')

print(fruits)  # Output: {'apple', 'orange', 'grape'} (no error, set remains unchanged)

In this example, the discard() method is used to remove the element 'banana' from the set fruits. As a result, 'banana' is no longer in the set. Then, we attempt to remove the element 'watermelon', which does not exist in the set. The discard() method does not raise an error and leaves the set unchanged.

Unlike the remove() method, which raises a KeyError if the element is not found in the set, the discard() method ensures that no error is raised when attempting to remove a non-existent element.