2 Ways to Remove Element If Exists in Python Set

0
23
2 Ways to Remove Element If Exists in Python Set

If you have a set of values and want to remove an element from the Set if it exists, check out this tutorial.

Python set remove if exists

Two ways to remove an element from the Set if it exists.

  1. Set.discard(): If an element exists, it removes from the Set, and if it does not exist, it won’t throw any error.
  2. set.remove(): If an element exists, it removes from the Set, and if it does not exist, it will throw an error.

Using set.discard() method

To remove an element from Set if it exists in Python, use the Set.discard() method. The Set.discard() is a built-in method that removes an element from the Set only if an element is present. If an element is not present in the Set, it does not throw any error or exception and prints the Set as it is.

data_set = {11, 21, 19, 46, 9}

data_set.discard(19)
print(data_set)

Output

{21, 9, 11, 46}

In this example, we removed element “19” from the Set. Since it exists in the Set, the discard() method removes it.

Python removes an element if it does not exist

If an element does not exist in the Set and try to remove that element using the discard() method, the original Set is not affected. Therefore, no errors or exceptions will be raised.

data_set = {11, 21, 19, 46, 9}

data_set.discard(20)
print(data_set)

Output

{19, 21, 9, 11, 46}

You can see that we get the same Set without any modifications.

Using set.remove() method

The Set.remove() is a built-in Python method that removes an element if it is present in the Set. It will throw an error if an element does not exist in the Set.

data_set = {11, 21, 19, 46, 9}

data_set.remove(21)
print(data_set)

Output

{19, 9, 11, 46}

The “21” element exists in the Set. That’s why it was removed from the Set.

Try to remove an element if it does not exist

If we try to remove an element that does not exist in the Set, we will get KeyError.

data_set = {11, 21, 19, 46, 9}

data_set.remove(10)
print(data_set)

Output

KeyError: 10

To prevent KeyError in our example, use the discard() method instead of the remove() method.

Conclusion

The “remove()” and “discard()” are two methods provided by Python sets to remove elements from the Set. The “remove” will raise a KeyError if an element is not present in the Set. “discard” will not raise an error.

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.