Set discard Python Method | Example code

Python set discard method remove single elements from the set. It removes the specified item from the set. This method returns None.

set.discard(value) 

Example Set discard Python

Simple example code.

num_set = {1, 2, 3, 4, 5}

num_set.discard(3)

print(num_set)

Output:

Set discard Python Method

Diffrence between Set discard() vs remove() vs pop() method

set.remove(item)

This operation removes elements from the set. If the element does not exist, it raises a KeyError. The remove(item) method returns None.

Read more: Python Set remove method

set.discard(item)

This operation also removes elements from the set. But If an element does not exist, it does not raise a KeyError. The discard(item) method returns None.

set.pop()

The python pop() method removes and returns an arbitrary element from the set. If there are no elements to remove, it raises a KeyError.

Read more: Python set pop method

Do comment if you have any doubts and suggestions on this Python set topic.

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.