Tutorial Study Image

Python discard()

The discard() function in python helps to remove or discard the specified element from the set only if the element is present.


s.discard(element) #where element may be a integer,string etc.
 

discard() Parameters:

The discard() function takes a single parameter. This method is similar to remove() method, the difference is that the remove() method raises an error if the given element is not present in the set, but discard() will not. 

Parameter Description Required / Optional
element The item to search for, and remove Required

discard() Return Value

The discard() method doesn't return anything. It just updates the set by removing specified element from the set.

Examples of discard() method in Python

Example 1: How discard() works in Python?


alphabets = {'a', 'b', 'c', 'd'}

alphabets .discard(c)
print('Alphabets = ', alphabets )

numbers.discard(e)
print('Alphabets = ', alphabets )
 

Output:


Alphabets =  {'a', 'b', 'd'}
Alphabets =  {'a', 'b', 'd'}

Example 2: Working of discard() in Python


alphabets = {'a', 'b', 'c', 'd'}
#Returns none
print(alphabets .discard(c))
print('Alphabets = ', alphabets )
 

Output:


None
Alphabets = {'a', 'b', 'd'}