Python Set - discard

The discard() method of the Python set class removes an element from a Python set object if the element is present in the set. The discard() method does not raise any exception if the element is not present.

Set Updated 16 Sep 2016 1 min read

Method signature

discard(element_in)

Method Overview

  • The discard() method removes an element from a Python set if the element is present in the set.
  • Unlike the remove() method of the set class, the discard() method does not raise a KeyException if the element is not found.

Parameters

element_in :The element that is to be removed from a Python set.

Example

python
# Example Python program that removes an element from a set

            # using the method discard()

            cars = {"Fossil fuelled", "Electric car", "Hydrogen car"}

            cars.discard("Fossil fuelled")

            print(cars)

Output

Output
{'Electric car', 'Hydrogen car'}