How does set discard() work in Python?

The built-in discard() method in Python is used to remove a specific item from a set.

It is important to note that this method differs from the remove() method, which does the same thing. However, unlike remove(), discard() will not raise an error if the specified item does not exist in the set that calls the method.

Syntax

set.discard(item)

Parameters and return value

This method requires a value that will be removed from the set to be passed as a parameter.

The return value of discard() is None.

Example 1

x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
x.discard('Cats')
print(x)

Example 2

#Passing a value that does not exist in the set
x = {'Cats', 'Dogs', 'Elephants', 'Seals'}
x.discard('Tigers')
print(x)
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources