Skip to content

Set discard Python Method | Example code

  • by

Python set discard method removes 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 or suggestions on this Python set topic.

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading