Python set Method - remove()

The remove() method in Python sets is used to remove a specified element from the set. If the specified element is not present in the set, the method raises a KeyError exception.

The syntax for the remove() method is as follows:

set_name.remove(element)
Sourc‮gi.www:e‬iftidea.com

Here, set_name is the name of the set from which we want to remove the element, and element is the element that we want to remove from the set.

Example:

# Creating a set
fruits = {"apple", "banana", "cherry"}

# Removing an element using remove()
fruits.remove("banana")

print("Remaining fruits:", fruits)   # Output: Remaining fruits: {'cherry', 'apple'}

In the above example, the remove() method is used to remove the element banana from the set fruits. The output shows that the element banana is removed from the set, and the remaining elements are apple and cherry. If we try to remove an element that is not present in the set, the method will raise a KeyError exception.