Python Set remove() Function
The Set remove()
method removes a specified element from the set.
note
If the specified element is not found in the set, the method raises a KeyError
exception.
Syntax
my_set.remove(element)
remove() Parameters
Python Set remove()
function parameters:
Parameter | Condition | Description |
---|---|---|
element | Required | An item you want to remove from the set |
remove() Return Value
Python Set remove()
function does not return any value: it modifies the set in-place.
Examples
Example 1: Remove an existing Element
Let's remove an element from a non-empty set:
my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # Output: {1, 2, 4, 5}
output
{1, 2, 4, 5}
Example 2: Remove an Element that Does Not Exist in the Set
If specified item does not exist in a set, remove()
method raises a KeyError
exception.
my_set = {1, 2, 3, 4, 5}
my_set.remove(10) # raises KeyError
output
Traceback (most recent call last):
File "main.py", line 2, in <module>
my_set.remove(10)
KeyError: 10
remove() method vs discard() method
discard()
and remove()
methods work in the same way. The only difference is that the remove()
method raises KeyError
, if specified item does not exist in a set.
my_set = {'Tom', 'Ryan', 'David'}
my_set.remove('Anna') # raises KeyError: 'Anna'
print(my_set)
output
Traceback (most recent call last):
File "main.py", line 2, in <module>
my_set.remove('Anna')
KeyError: 'Anna'
While discard()
method does nothing.
my_set = {'Tom', 'Ryan', 'David'}
my_set.discard('Anna') # nothing happens
print(my_set) # Output: {'David', 'Tom', 'Ryan'}
output
{'David', 'Tom', 'Ryan'}