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.")
Mission
0 / 1
Which function does not raise an error when trying to remove an element that is not present in a Python set?
add()
remove()
discard()
clear()
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result