Python Remove items from Set


Remove items from Set

One of the property of the set is that it is unchangeable. But, we can still add or remove items from the set. Python has some built in methods to remove the items from the set. We will learn different approaches and methods we can use to delete the items from the set.

Remove items from Set

The remove() method

The remove() is a built-in method to remove the specific item from the set. The element to remove is passed as an argument to the set. It can accept only one element as an argument, means i can delete only one element at a time.

It will raise an error if the item does not exist in the set. To avoid the error, we can use the membership operator “in” to check if the item is available in the set.

In [1]:
names = {"Bill", "Steve", "Tim"}
names.remove("Steve")
print(names)
{'Tim', 'Bill'}

Raises an error if item does not exist.

In [2]:
names = {"Bill", "Steve", "Tim"}
names.remove("Oliver")
print(names)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-87264aeb5a89> in <module>
      1 names = {"Bill", "Steve", "Tim"}
----> 2 names.remove("Oliver")
      3 print(names)

KeyError: 'Oliver'

Use membership operator to avoid error.

In [3]:
names = {"Bill", "Steve", "Tim"}

if ("Oliver" in names):
    names.remove("Oliver")

print(names)
{'Tim', 'Bill', 'Steve'}

The discard() method

The discard() method is also used to remove the specific item from the set. It is similar to the remove() method, the only difference is that it will not raise an error if the item does not exist.

In [1]:
names = {"Bill", "Steve", "Tim"}
names.discard("Steve")
print(names)
{'Tim', 'Bill'}

Do not raise an error if item does not exist.

In [2]:
names = {"Bill", "Steve", "Tim"}
names.discard("Oliver")
print(names)
{'Tim', 'Steve', 'Bill'}

Delete multiple items using remove() and discard()

To delete multiple items with the remove() or discard() method, we can use this method with the for loop. For loop will iterate over items one by one and these methods will remove the items.

The remove() method

In [1]:
names = {"Bill", "Steve", "Tim"}
names_to_remove = ["Bill", "Steve"]

for name in names_to_remove:
    names.remove(name)

print(names)
{'Tim'}

The discard() method

In [2]:
names = {"Bill", "Steve", "Tim"}
names_to_remove = ["Bill", "Steve"]

for name in names_to_remove:
    names.discard(name)

print(names)
{'Tim'}

The pop() method

The pop() method will remove the random item from the set and return the removed item. In case the set is empty, the KeyError is raised.

In [1]:
names = {"Bill", "Steve", "Tim"}
item_removed = names.pop()

print(item_removed)
print(names)
Tim
{'Bill', 'Steve'}

Using pop with Empty Set.

In [2]:
names = set()
item_removed = names.pop()

print(item_removed)
print(names)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-a3e6c040bed9> in <module>
      1 names = set()
----> 2 item_removed = names.pop()
      3 
      4 print(item_removed)
      5 print(names)

KeyError: 'pop from an empty set'

The difference() or difference_update() method

The difference() and difference_update() allows us to remove multiple items from the set. While using these methods, we need not to use the for loop to iterate over the elements. We just need to pass the iterable as the set or list, etc. All those elements will be removed from the original set.

The difference() method will return the new set but the differeence_update() method will update the original set.

The difference() method

In [1]:
names = {"Bill", "Steve", "Tim"}
names_to_remove = ["Bill", "Steve"]

names = names.difference(names_to_remove)

print(names)
{'Tim'}

The difference_update() method

In [2]:
names = {"Bill", "Steve", "Tim"}
names_to_remove = {"Bill", "Steve"}

names.difference_update(names_to_remove)

print(names)
{'Tim'}

Using the – Operator

The – operator works in the same way as the difference() method, the only difference is that, it will work with sets only and the difference() method can work with the other iterables like list, etc.

The – operator works with set only.

In [1]:
names = {"Bill", "Steve", "Tim"}
names_to_remove = {"Bill", "Steve"}

names = names - names_to_remove

print(names)
{'Tim'}

The – operator will not work with list.

In [2]:
names = {"Bill", "Steve", "Tim"}
names_to_remove = ["Bill", "Steve"]

names = names - names_to_remove

print(names)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-953b45d2ef8c> in <module>
      2 names_to_remove = ["Bill", "Steve"]
      3 
----> 4 names = names - names_to_remove
      5 
      6 print(names)

TypeError: unsupported operand type(s) for -: 'set' and 'list'

The del keyword

The del keyword is used to delete the set completely.

Deletes the set completely.

In [1]:
names = {"Bill", "Steve", "Tim"}
del names
print(names)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c8886076861c> in <module>
      1 names = {"Bill", "Steve", "Tim"}
      2 del names
----> 3 print(names)

NameError: name 'names' is not defined

The clear() method

The clear() method removes all the items from the set. The set variable still exists with no content.

In [1]:
names = {"Bill", "Steve", "Tim"}
names.clear()
print(names)
set()

Conditionally remove items from the set

To conditionally remove items from the set, we have to use the if condition for the items that we want to remove. Note: For this approach to work, we need to make sure, set is converted to list for the loop to work. Otherwise, it will throw an error.

Conditionally remove items from the set by converting set to list for loop.

In [1]:
names = {"Bill", "Steve", "Tim"}

for name in list(names):
    if name.startswith("B"):
        names.remove(name)

print(names)
{'Steve', 'Tim'}

Error in case we don’t convert set to list for loop.

In [2]:
names = {"Bill", "Steve", "Tim"}

for name in names:
    if name.startswith("B"):
        names.remove(name)

print(names)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-2-98d84e517fb2> in <module>
      1 names = {"Bill", "Steve", "Tim"}
      2 
----> 3 for name in names:
      4     if name.startswith("B"):
      5         names.remove(name)

RuntimeError: Set changed size during iteration

Quick Recap

Here is a quick recap of the different approaches we can use to remove items from a set.

ApproachDetail
The remove() methodRemove a specific item.
The discard() methodRemoves a specific item without error.
Delete multiple items using remove() and discard()The for loop is used.
The pop() methodRemoves and returns random item.
The difference() or difference_update() methodRemove Multiple Items.
The del keywordDeletes set completely.
The clear() methodEmpty the set.
Conditionally remove items from the setUsing for and if statement

References:

  1. Python Set remove()
  2. How to Remove Items from Python Sets