The remove() function allows the deletion of an item from the set.
colors_set = {"Red", "Blue", "Green"}
colors_set.remove("Blue")
print(colors_set)
{'Red', 'Green'}
In the above example, we removed the color "Blue" from a set using the remove() function. You can see the output "Blue" color removed from the set, and the remaining color items are displayed.
You can also delete an item from a set using the discard() function.
colors_set = {"Red", "Blue", "Green"}
colors_set.discard("Red")
print(colors_set)
{'Blue', 'Green'}
Here, we removed the "Red" color item from a set using the discard() function.
An error will occur if you try to delete an item that does not exist in a set.
colors_set = {"Red", "Blue", "Green"}
colors_set.remove("Purple")
print(colors_set)
KeyError: 'Purple'
In the above example, removing the "Purple" color from a set resulted in a KeyError, because the "Purple" color does not appear in the given set.
The pop() function removes the last item from the set, but remember that the set is unordered, so you don't know which item to delete from set.
A pop() function returns a removed item after removing an item from a set.
colors_set = {"Red", "Blue", "Green"}
color = colors_set.pop()
print(color)
print(colors_set)
Blue
{'Red', 'Green'}
Here, we removed an item from a set using the pop() function.
Remove all items from the set with the clear() function.
colors_set = {"Red", "Blue", "Green"}
colors_set.clear()
print(colors_set)
set()
In the above example, we get the empty set after removing all the items from the set using the clear() function.
Use the del keyword to delete the entire set.
colors_set = {"Red", "Blue", "Green"}
del colors_set
print(colors_set)
NameError: name 'colors_set' is not defined
We removed the entire set using the del keyword. You can see the output "NameError: name 'colors_set' is not defined".