set.remove(element) removes a matching element from a set and returns None. If the element is not present, Python raises KeyError.
Use discard() when a missing element should be ignored. Both methods modify the original mutable set.
my_set={'a','b','c','x','k'}
my_set.remove('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.remove('y')
my_set={'a','b','c','x','k'}
my_set.discard('y')
print(my_set)
Output
{'x', 'c', 'a', 'k', 'b'}
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.