Python set remove() Method

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.

Set order: sets are unordered. Whenever an example prints a set, the displayed element order can differ between runs or Python environments.
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.

Removing not available element

This will generate error KeyError
my_set={'a','b','c','x','k'}
my_set.remove('y')

Difference between remove() and discard()

If the element is not present then discard() will not generate error.
my_set={'a','b','c','x','k'}
my_set.discard('y')
print(my_set)
Output
{'x', 'c', 'a', 'k', 'b'}

All Set Methods Questions with solutions on set discard()


Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer