Removing Items from a Set
Items can be removed from a set using the remove()
or discard()
methods. The pop()
method can also be used to remove an arbitrary item.
Using remove()
Example: Removing an Item
# Removing an item from a set
fruits = {"Apple", "Banana", "Cherry"}
fruits.remove("Banana")
print("Set after remove:", fruits)
Output (Order may vary)
Set after remove: {'Cherry', 'Apple'}
Using discard()
Example: Discarding an Item
# Discarding an item from a set
fruits.discard("Orange") # Does not raise an error if item doesn't exist
print("Set after discard:", fruits)
Output
Set after discard: {'Cherry', 'Apple'}
Using pop()
Example: Popping an Item
# Popping an item from a set
popped_item = fruits.pop()
print("Popped Item:", popped_item)
print("Set after pop:", fruits)
Note: Since sets are unordered, you don't know which item gets popped.
Popped Item: Cherry
Set after pop: {'Apple'}
Explanation: The remove()
method removes the specified item but raises a KeyError
if the item doesn't exist. The discard()
method also removes the specified item but does not raise an error if the item doesn't exist. The pop()
method removes an arbitrary item because sets are unordered.