Python Set remove() Method

The remove() method deletes the specified element from a set. If the element doesn’t exist, it raises a KeyError.

Syntax

set.remove(element)

Parameters

element (Required): The element to be removed from the set.

Return Value

Doesn’t return any value (i.e., returns None). It modifies the original set in-place.

Example 1: Removing an Item

fruits = {"apple", "banana", "mango"}
fruits.remove("apple")
print(fruits) # Output: {'mango', 'banana'}

Python sets are unordered, so the elements may appear in a different order each time you print them.

Example 2: Removing a non-existent Item

If you try to remove an item that is not present in the set, it raises a KeyError.

fruits = {"apple", "banana", "mango"}
fruits.remove("orange") # Raises KeyError
print(fruits)

If you are not sure whether an element exists in the set, use the discard() method instead. It removes the element it it present and does nothing it is missing.

Also Read: Python Set discard() Method