The Python Set remove() method is used to remove a specified element from the set. If the element is present in the set then it removes it. If the element is not found then it raises a KeyError exception.
The discard() method which also removes an element but does not raise an error if the element is missing where as the remove() method ensures that the specified element must exist in the set.
This method is useful when we need to enforce the presence of an element before removing it by ensuring the set's integrity by handling unexpected missing elements explicitly.
SyntaxFollowing is the syntax and parameters of Python Set remove() method.
set.remove(element)Parameter
This method accepts only one parameter i.e. element , which the element to be removed from the set if present.
Return valueThis method does not return any value.
Example 1Following is the example which shows how to remove an element that exists in the set −
# Define a set my_set = {1, 2, 3, 4, 5} # Remove an element my_set.remove(3) print(my_set)Output
{1, 2, 4, 5}Example 2
This example is trying to remove an element that doesn't exist in the set and raises a KeyError −
# Define a set my_set = {1, 2, 3} # Try to remove a non-existing element try: my_set.remove(4) except KeyError as e: print(f"Error: {e}")Output
Error: 4Example 3
Now, in here we use a loop to remove multiple elements from a set.
# Define a set my_set = {1, 2, 3, 4, 5} # Remove multiple elements elements_to_remove = {2, 4} for elem in elements_to_remove: my_set.remove(elem) print(my_set)Output
{1, 3, 5}Example 4
In this example we use list comprehension and define the condition in list comprehension to remove elements based on that condition −
# Define a set my_set = {1, 2, 3, 4, 5} # Remove elements greater than 3 my_set = {elem for elem in my_set if elem <= 3} print(my_set)Output
{1, 2, 3}
python_set_methods.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4