Click for All Topics
Syntax
set_name.discard(element)
Parameter –
Example 1- Discard an element that is present in the set
my_set={1,2,3,4}
print(my_set)
my_set.discard(3)
print(my_set)
# Output -
# {1,2,3,4} # my_set before removing element
# {1,2,4} # my_set after removing element
print()
function.Example 2- Discard an element that does not exist in the set
my_set=set() # empty set
for i in range(1,6):
my_set.add(i)
print(my_set)
my_set.discard(7)
print(my_set)
# Output -
# {1, 2, 3, 4, 5} # before removing element my_set
# {1, 2, 3, 4, 5} # after removing element my_set
set()
function.add()
method.Example 3- Discard even element from a set
s={10,11,12,13,14,15,16,17,18,19}
s1={10,11,12,13,14,15,16,17,18,19}
print(s)
for i in s1:
if i%2==0:
s.discard(i)
print(s)
# Output -
# {10, 11, 12, 13, 14, 15, 16, 17, 18, 19} # before discard element from set s
# {11, 13, 15, 17, 19} # after discard element from set s
Example 4- Discard string from a set
original_set={'hello','this', 'is', 'edSlash'}
print(original_set)
discarded_element=original_set.discard('hello')
print(discarded_element)
print(original_set)
# Output -
# {'hello','this','is','edSlash'}
# None
# {'this', 'is', 'edSlash'}
Example 5- Discard method trying to pass two arguments
s={'I','am','anurag', 'dubey'}
s.discard('anurag','dubey')
print(s)
# Output -
# Traceback (most recent call last):
# File "/home/main.py", line 2, in
# s.discard('anurag','dubey')
# TypeError: set.discard() takes exactly one argument (2 given)
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India