In Python, you can remove items from a set using several methods. Here’s how each one works:
Removing a Specific Item with remove()
The remove()
method deletes a specific item from the set. If the item doesn’t exist, it raises a KeyError
.
data_set = {1, 2, 3, 4, 5}
data_set.remove(4)
print(data_set) # Output: {1, 2, 3, 5}
# Trying to remove an item that doesn't exist
# data_set.remove(6) # Raises KeyError
Removing a Specific Item with discard()
The discard()
method also deletes a specific item from the set, but if the item doesn’t exist, it doesn’t raise an error.
data_set = {1, 2, 3, 4, 5}
data_set.discard(4)
print(data_set) # Output: {1, 2, 3, 5}
data_set.discard(6) # No error if 6 isn't in the set
Removing and Returning a Random Item with pop()
The pop()
method removes and returns a random item from the set. Since sets are unordered, you won’t know which item will be removed.
data_set = {10, 20, 30, 40, 50}
removed_item = data_set.pop()
print("Removed item:", removed_item) //50
print("Set after pop:", data_set) // {10, 20, 30, 40}
# Output will vary because pop removes a random item
Removing All Items with clear()
The clear()
method removes all items from the set, leaving it empty.
data_set = {1, 2, 3, 4, 5}
data_set.clear()
print(data_set) # Output: set()