Python Set remove()

Python Set remove() method

Python Set remove() - Remove element

Python Set remove() method removes the specified element from the set.

In this tutorial, we will learn the syntax and usage of remove() method of Set class, with examples.

Syntax of Set remove()

The syntax to call remove() method on a set is

set.remove(element)

Parameters

Set remove() method takes one parameter.

ParameterDescription
elementRequired
Any valid Python object.
This object is removed from the set.

Return value

Set remove() method returns None.

Exceptions

Set remove() method raises KeyError exception if the specified element is not present in the Set.

Please note that the remove() method modifies the original set.

Examples

1. Removing element ‘b’ from the Set in Python

In this example, we will take a set with three items and remove an element from the set. The element we are removing, is present in the set.

Python Program

# Initialize set
set_1 = {'a', 'b', 'c'}

# Remove() method
set_1.remove('b')

print(set_1)
Run Code Copy

Output

{'a', 'c'}

2. Removing element from Set, where the element is not present in the Set, in Python

In this example, we will try to remove an element that is not present in the set using remove() method on the Set object.

Python Program

# Initialize set
set_1 = {'a', 'b', 'c'}

# Remove() method
x = set_1.remove('f')

print(x)
Run Code Copy

The remove() method raises a KeyError exception as shown in the following output.

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 5, in <module>
    x = set_1.remove('f')
KeyError: 'f'

So, before you try to remove an element from the set using remove() method, first check if the element is present in the set or not. Attempt to remove the element only if present, and in the else block you can have code to handle the situation if the element is not present in the set.

In the following program, we will use Python if else statement to check if the element is present, and then we shall remove the element from the set.

Python Program

set_1 = {'a', 'b', 'c'}

item = 'f'
if item in set_1:
    set_1.remove('f')
else:
    print('Element is not in set. Action required.')
Run Code Copy

Output

Element is not in set. Action required.

Summary

In this Python Set Tutorial, we learned how to use Set remove() method to remove element from a set, with the help of well detailed Python programs.

Related Tutorials

Code copied to clipboard successfully 👍