Python Set remove()

Python Set – Remove Item

Python Set - Remove Item

Python Set remove() method is used to remove the specified item/element from the set.

remove() methods returns None. It modifies the set on which you are calling the remove() method.

In this tutorial, we will learn the usage of remove() method of Set class, using different scenarios.

Example 1: Remove an Item from Set

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

Output

{'a', 'c'}

Example 2: Remove an Item Not present in the Set

In this example, we will try to remove an item that is not present in the set. Python will throw a KeyError.

Python Program

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

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

print(x)
Run

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 item from set, first check if the item is actually present or not. Attempt to remove the item only if present, and in the else block you can have code to handle the situation if the item is not present in the set.

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

Python Program

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

item = 'f'
if item in set_1:
    set_1.remove('f')
else:
    print('item not in set')
Run

Output

item not in set

Summary

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