Tutorial Study Image

Python remove()

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
 

remove() Parameters:

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

remove() Return Value

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.

Examples of remove() method in Python

Example 1:  How to remove an element from 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'}

Example 2: Try to remove an element that is not in the set


# 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'