Python .remove()
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:
Contribute to Docs
- 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.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours