Python Set discard() Method

The discard() method removes the specified element from a set. Unlike the remove() method, it does not raise an error if the element doesn’t exist in the set.

Syntax

set.discard(element)

Parameter

element (required): The item to remove from the set.

Return Value

Returns None. It updates the set in-place by removing the element, if it is present.

Example 1: Removing an Item

fruits = {"apple", "banana", "mango", "orange"}
fruits.discard("banana")
print(fruits) # Output: {'mango', 'apple', 'orange'}

Python sets are unordered, so the element may appear in a different order each time you print them.

Example 2: Removing an non-existent item

If you try to remove an element that doesn’t exist in a set using the discard() method, it simply does nothing and the program continues without raising any errors.

fruits = {"apple", "banana", "mango", "orange"}
fruits.discard("coconut") # Raises no error
print(fruits) # Output: {'apple', 'mango', 'orange', 'banana'}

When to use discard() vs remove()

  • Use discard() when you are unsure if the element is in the set and want to avoid raising an error.
  • Use remove() when you expect the element in the set and want an error raised if it isn’t.