Python Set remove()
Python Set x.remove(e)
method removes the element e
from the set x
.
In this tutorial, we will learn the syntax of set.remove() method and go through examples covering different scenarios for the arguments that we pass to remove() method.
Syntax
The syntax of set.remove() method is
set.remove(e)
where
Parameter | Description |
---|---|
e | The element to be removed from the set. |
Examples
1. Remove element from set
In the following program, we will take a set x
and remove an element specified by e
from the set.
Python Program
x = {'apple', 'banana', 'cherry'}
e = 'banana'
x.remove(e)
print('Resulting set :', x)
Program Output
Resulting set : {'apple', 'cherry'}
2. Remove element from set (element not present in set)
In the following program, we try to remove an element from set, where the element is not present in the set.
Python Program
x = {'apple', 'banana', 'cherry'}
e = 'mango'
x.remove(e)
print('Resulting set :', x)
Program Output
Traceback (most recent call last):
File "example.py", line 3, in <module>
x.remove(e)
KeyError: 'mango'
If specified element is not present in the set, then set.remove() method raises KeyError.
Conclusion
In this Python Tutorial, we learned about Python set method remove(). We have gone through the syntax of remove() method, and its usage with example programs.