.remove()
Dashrath_Patel3 total contributions
Published May 18, 2024
Contribute to Docs
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:
# Creating a setmy_set = {1, 2, 3, 4, 5}# Removing '4' from the setmy_set.remove(4)# Printing the modified setprint(my_set)# Removing '6' from the setmy_set.remove(6)# Printing the modified setprint(my_set)
The above code produces the following output:
{1, 2, 3, 5}KeyError: 6
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:
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.