Lecture
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.")
Lessons in this chapter · Dictionary and Set Data Types for Managing Structured Data
- 1. Managing Structured Data with Dictionaries
- 2. Utilizing Values Within a Dictionary
- 3. Adding and Modifying Elements in a Dictionary
- 4. Removing a Specific Element from a Dictionary
- 5. Multiple-choice quiz
- 6. Handling Dictionary KeyError Exceptions
- 7. Checking Key Existence in a Dictionary
- 8. Safely Checking for Key Existence in a Dictionary
- 9. Multiple-choice quiz
- 10. Set Data Type that Does Not Allow Duplicate Values
- 11. Intersection, Union, Difference Operations
- 12. Adding Elements to a Set
- 13. Removing Elements from a Set
- 14. Utilizing Values within a Set
- 15. Differences Between Shallow and Deep Copy
- 16. Coding Quiz - Safely Extract Values from a Dictionary
- 17. Multiple-choice quiz
- 18. Fill-in-the-blank quiz
Quiz
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
Design
Upload
Notes
Favorites
Help