Python set discard() Method

set.discard(element) removes an element from a set if it is present and returns None. If the element is missing, discard() does not raise KeyError.

Use remove() instead when a missing value should be treated as an error. 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.discard('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 not generate any error (KeyError)
my_set={'a','b','c','x','k'}
my_set.discard('y')

Difference between discard() and remove()

If the element is not present then discard() will not generate error, but remove() method will raise error.
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

Use Case: Safely Removing Items

my_set = {'apple', 'banana', 'cherry'}
my_set.discard('banana')  # Safely removes banana
my_set.discard('grape')   # No error, even though grape is not present

Example 1: Using discard() in a Loop

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}

Example : Discarding Items Conditionally

my_set = {'apple', 'banana', 'cherry'}
if 'banana' in my_set:
    my_set.discard('banana')
print(my_set)  # Output: {'apple', 'cherry'}

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