The remove() function in python helps to remove the specified element from the set. If the given element is not found in the set, the method will raise a KeyError.
set.remove(element) #where element which is to be remove
The remove() function takes a single parameter. This method is similar to discard(), the difference is that the discard() method will not raise an error even if the element is not found and the set remains unchanged.
Parameter | Description | Required / Optional |
---|---|---|
element | The element to be removed from the set. | Required |
This method doesn't return any value. It just updates the set by removing a particular element. This method will raise a KeyError if the given element is not found in the set.
# flowers set
flowers = {'Dalia', 'Rose', 'Lotus', 'Sunflower'}
# 'Lotus' is removed
flowers.remove('Lotus')
# Updated flowers set
print('Updated flowers Set: ', flowers)
Output:
Updated flowers Set:{'Dalia', 'Rose', 'Sunflower'}
# flowers set
flowers = {'Dalia', 'Rose', 'Lotus', 'Sunflower'}
# 'Lotus' is removed
flowers.remove('cat')
# Updated flowers set
print('Updated flowers Set: ', flowers)
Output:
Traceback (most recent call last): File "", line 5, in flowers.remove('cat') KeyError: 'cat'