Python sets are an efficient way to store unique, unordered items. While adding items to a set is straightforward, removing items also offers a variety of methods. This article will guide you through the different techniques available to remove items from a set in Python.
Remove single set item using remove() Method
The remove() method removes a specified item from the set. If the item is not found, it raises a KeyError.
set = {1, 2, 3, 4, 5}
set.remove(3)
print(set)
Output
{1, 2, 4, 5}
In this example, the number 3 is removed from the numbers set. If 3 were not present in the set, a KeyError would be raised.
Let's take a look at other methods of removing set items in python:
Table of Content
Using discard() Method
The discard() method also removes a specified item from the set. Unlike remove(), it does not raise an error if the item is not found.
set = {1, 2, 3, 4, 5}
set.discard(3)
print(set)
Output
{1, 2, 4, 5}
Here, the number 3 is removed from the set. If 3 were not present, the set would remain unchanged without raising an error.
Using pop() Method
The pop() method removes and returns an arbitrary item from the set. If the set is empty, it raises a KeyError.
set = {1, 2, 3, 4, 5}
item = set.pop()
print(item)
print(set)
Output
1
{2, 3, 4, 5}
In this example, an arbitrary item is removed from the numbers set and stored in the item variable. The remaining items in the set are then printed. Since sets are unordered, the item removed by pop() can be any element from the set.
Remove all set items using clear() Method
The clear() method removes all items from the set, resulting in an empty set.
s = {1, 2, 3, 4, 5}
s.clear()
print(s)
Output
set()
Here, the clear() method removes all elements from the numbers set, leaving it empty.
Removing Items Using Set Difference
You can also remove multiple items by using the set difference method. This does not modify the original set but returns a new set with the specified items removed.
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4}
res = set1 - set2
print(res)
Output
{1, 2, 5}
In this example, the items 3 and 4 are removed from the numbers set, resulting in a new set res.
Removing Items Using Set Comprehension
Set comprehension can be used to create a new set excluding specific items.
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4}
res = {i for i in set1 if i not in set2}
print(res)
Output
{1, 2, 5}
Here, a new set res is created by including only those items from the set1 that are not in the set2.