element : matching element to be discarded from setmy_set={'a','b','c','x','k'}
my_set.discard('x')
print(my_set)
Output is here
{'c', 'a', 'k', 'b'}
In above code x is deleted from my_set.
KeyError)
my_set={'a','b','c','x','k'}
my_set.discard('y')
my_set = {1, 2, 3}
my_set.discard(4) # No error, even if 4 is not in the set
my_set.remove(4) # Raises KeyError because 4 is not in the set
my_set = {'apple', 'banana', 'cherry'}
my_set.discard('banana') # Safely removes banana
my_set.discard('grape') # No error, even though grape is not present
my_set = {1, 2, 3, 4, 5}
elements_to_remove = [2, 6, 3]
for item in elements_to_remove:
my_set.discard(item) # Safely removes elements, no error if not present
print(my_set) # Output: {1, 4, 5}
my_set = {'apple', 'banana', 'cherry'}
if 'banana' in my_set:
my_set.discard('banana')
print(my_set) # Output: {'apple', 'cherry'}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.