The most Pythonic way to remove an element from a set, if it exists, is using the .discard() method.
sample_set = {11, 21, 19, 46, 9} # Remove the element if it exists sample_set.discard(19) print(sample_set) # Output: {9, 11, 21, 46}
In this code, element “19” exists, and we removed it from a set.
Removing an element if it does not exist
If the element is not present in the set, it does not raise any error or exception, and the set remains unchanged.
sample_set = {11, 21, 19, 46, 9} sample_set.discard(44) print(sample_set) # Output: {9, 11, 19, 21, 46} (No changes since 44 was not in the set)
Since the “44” element does not exist in the Set, it returns the set as it is.
Set with Mixed Types
A set can hold heterogeneous hashable data types. So, there can be mixed-type elements.
main_set = {1, "apple", (2, 3), None} main_set.discard("apple") print(main_set) # Output: {1, None, (2, 3)}
In this code, we removed the string element “apple” from the set. All the other elements remain unchanged.
Empty Set
If the Set is empty and you still try to remove an element from it, it will return an empty Set and does not throw any exception.
empty_set = set() # or {} empty_set.discard(1) print(empty_set) # Output: set()
Set with a single element
If the set contains only a single element, removing it will return an empty set.
main_set = {42} main_set.discard(42) print(main_set) # Output: set() # Now empty
Using Set.remove() method
There is an alternate way to remove an element called the “Set.remove()” method. It deletes the specified item from the set, but it will throw a KeyError if the element does not exist in the set.
So make sure that the element exists before removing or handling the exception using a try-except block.
sample_set = {11, 21, 19, 46, 9} try: sample_set.remove(19) except KeyError: print("Element not found in the set.") print(sample_set) # Output: {21, 9, 11, 46}
Since element “19” exists, it was successfully deleted.
KeyError scenario
Let’s check out the scenario where an element does not exist and throws the KeyError exception.
sample_set = {11, 21, 19, 46, 9} try: sample_set.remove(44) print(sample_set) except KeyError: print("Input element does not exist in the set") # Output: Input element does not exist in the set
To prevent KeyError in our example, use the discard() method instead of the remove() method.