Removing Elements from a Set
To remove a specific element from a set, use the remove()
or discard()
functions.
Removing Elements with remove()
The remove()
function removes an element specified within its parentheses from the set.
If the specified element is not present in the set, it raises a KeyError.
Removing an Element using remove()
my_set = {1, 2, 3, 4}
my_set.remove(3)
print("my_set:", my_set)
# {1, 2, 4}
Removing Elements with discard()
Similarly, discard()
removes an element specified within its parentheses from the set.
Unlike remove()
, discard()
does not raise an error if the specified element is not present in the set.
Removing an Element using discard()
my_set = {1, 2, 3, 4}
my_set.discard(3)
print("my_set:", my_set)
# {1, 2, 4}
my_set.discard(5)
# 5 is not in the set, so the operation is executed without any error
Handling Exceptions with remove()
You can handle exceptions raised by the remove()
function using a try-except
block as shown below.
Handling Exceptions using remove()
my_set = {1, 2, 3, 4}
try:
my_set.remove(6)
# Raises KeyError since 6 is not in the set
except KeyError:
print("The element does not exist in the set.")
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.