Python Set remove method | Example code

Use the remove() method to removes 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:

Python Set remove method

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 and suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.