Remove Items
Lesson 5 of 11 in Coddy's Sets in Python course.
Python provides several methods to remove elements from a set, each with its own characteristics and use cases:
Using remove() Method:
The
remove()method removes a specified element from the set. If the element is not found, it raises aKeyError.fruits = {"apple", "banana", "cherry"} fruits.remove("banana") print(fruits) # Output: {'apple', 'cherry'}Using discard() Method:
The
discard()method also removes a specified element from the set, but it does not raise an error if the element is not found.fruits = {"apple", "banana", "cherry"} fruits.discard("banana") print(fruits) # Output: {'apple', 'cherry'} fruits.discard("date") # No error raised print(fruits) # Output: {'apple', 'cherry'}Using pop() Method:
The
pop()method removes and returns an arbitrary element from the set. Since sets are unordered, you do not know which element will be removed. If the set is empty, it raises aKeyError.fruits = {"apple", "banana", "cherry"} item = fruits.pop() print(item) # Output: (one of the elements, e.g., 'apple') print(fruits) # Output: (the set without the popped element, e.g., {'banana', 'cherry'})Using clear() Method:
The
clear()method removes all elements from the set, resulting in an empty set.fruits = {"apple", "banana", "cherry"} fruits.clear() print(fruits) # Output: set()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyWrite a function named remove_item that gets a set and an item and removes this item from the set, if it does not exist, don't raise an error.
Try it yourself
def remove_item(s, item):
# Write code here