Contents
Python Set – Remove Specific Item
You can remove a specific item from Python Set using discard() method of Set class.
In this tutorial, we will learn how to use discard() method to remove one or more specific items from a Set in Python.
Example 1: Remove Item from Set
In this example, we take a set of elements and try using discard() method to remove an element that is present in the set.
Python Program
#initialize sets
set_1 = {'a', 'b', 'c', 'd'}
#remove element from set
set_1.discard('c')
print(set_1)
Run Output
{'a', 'd', 'b'}
The element that is passed to the discard() method has been removed from the set.
Example 2: Remove an element Not present in Set
If you try removing an element that is not present in set, the original set is unchanged and no error is thrown.
In this example, we shall take a set, and try removing an element that is not present in the set.
Python Program
#initialize sets
set_1 = {'a', 'b', 'c', 'd'}
#remove element from set
set_1.discard('k')
print(set_1)
Run Output
{'a', 'd', 'b', 'c'}
Summary
In this tutorial of Python Examples, we learned how to user discard() method to remove an item from the set.