Python | Sets | .remove() | Codecademy
In Python, the .remove() method removes a specified element from a set. If the element is not found, it raises a KeyError.
Syntax
set.remove(element)
set: The set from which the element is to be removed.element: The element to be removed from the set.
Example
The below example shows the usage of the .remove() method:
my_set = {1, 2, 3, 4, 5}
my_set.remove(4)
print(my_set)
my_set.remove(6)
print(my_set)
The above code produces the following output:
In the above example, the .remove() method raises a KeyError since the element 6 doesn’t exist in my_set.
Codebyte Example
Below is a codebyte example demonstrating the use of the .remove() method: