Remove Set Items

You can remove items from a set using methods like remove(), discard(), or pop(). Note that pop() will remove a random item because sets are unordered.

Using remove() Method:

The remove() method removes a specified item. If the item does not exist, it raises a KeyError.

Python
fruits = {"apple", "banana", "cherry"}

# Remove "banana"
fruits.remove("banana")
print(fruits)  # Output: {"apple", "cherry"}

Using discard() Method:

The discard() method removes a specified item without raising an error if the item does not exist:

Python
fruits = {"apple", "banana", "cherry"}

# Discard "banana"
fruits.discard("banana")
print(fruits)  # Output: {"apple", "cherry"}

# Discard "orange" (no error if not present)
fruits.discard("orange")
print(fruits)  # Output: {"apple", "cherry"}

Using pop() Method:

The pop() method removes and returns a random item from the set:

Python
fruits = {"apple", "banana", "cherry"}

# Pop a random item
removed_item = fruits.pop()
print(removed_item)
print(fruits)

Removing items from a set provides flexibility, depending on whether you need to avoid errors or need to work with random elements.