Use the remove() method to remove the specified element from the set in Python. This method removes a specified element from the set.
set.remove(item)
Note: this method will raise an error if the passed specified element value does not exist in the set.
Python example remove element form set
Simple example code, how to remove an element in a set.
languages = {'Python', 'Java', 'JavaScript'}
# remove JavaScript from the set
languages.remove('JavaScript')
print(languages)
Output:
Another example
The discard() method also removes the specified element from the set.
languages = {'Python', 'Java', 'JavaScript'}
# remove JavaScript from the set
languages.discard('JavaScript')
print(languages)
Output: {‘Java’, ‘Python’}
Diffrence between set.discard() vs set.remove()
Answer: The difference between set.discard() and set.remove() is that set.discard() doesn’t raise an error whereas set.remove() raises a KeyError if the element to be removed is not a member of the set.
Do comment if you have any doubts or suggestions on this Python set tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.