Python Set remove() Method

The set.remove() method removes the specified element from the set. If the specified element is not found, raise an error.

Syntax:

set.remove(element)

Parameters:

element: The element to be removed from the set.

Return Value:

No return value.

The following example demonstrates removing element using the set.remove() method.

Example:
cities = {'Delhi','Chicago','New York'}
cities.remove('Delhi')
print(cities)

cities.remove('Chicago')
print(cities)

cities.remove('New York')
print(cities)
Output
{'New York', 'Chicago'}
{'New York'}
{}

If the argument passed in the remove function is not found in the set, KeyError exception is thrown.

Example:
cities = {'Delhi','Chicago','New York'}
cities.remove('Honk Kong')
Output
Traceback (most recent call last):
cities.remove('Hong Kong')
KeyError: 'Hong Kong'

To avoid the error, discard() method can be used. It removes the element from the set if the element is found in the set, and if the element is not found, the set remains unchanged.

Want to check how much you know Python?