Python Remove Set Element If Exists

Here are the two ways to remove an element of a set if it exists in Python:

  1. Using discard() method
  2. Using remove() method

Method 1: Using discard() method

The Set.discard() method is used to remove an element from the set only if an element is present.

If the element is not present in the set, it does not raise any error or exception, and the set remains unchanged.

Visual Representation

Python Remove Set Element If Exists using discard() method

Example

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

# Remove the element if it exists
sample_set.discard(19)

print(sample_set)

Output

{21, 9, 11, 46}

Removing an element if it does not exist

Removing an element if it does not exist using discard()

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

# Remove the element if it exists
sample_set.discard(44)

print(sample_set)

Output

{19, 21, 9, 11, 46}

Method 2: Using remove() method

The Set.remove() method is used to remove the specified item from the set.

It will throw a KeyError if the element does not exist in the set.

Visual Representation

Using remove() method

Example

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

# Remove the element, will raise an error if the element is not found
try:
 sample_set.remove(19)
except KeyError:
 print("Element not found in the set.")
 
print(sample_set)

Output

{21, 9, 11, 46}

Removing an element if it does not exist

Removing an element if it does not exist using remove()

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

# Remove the element, will raise an error if the element is not found
try:
 sample_set.remove(44)
 print(sample_set)
except KeyError:
 print("Element not found in the set.")

Output

Element not found in the set.

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

Difference between Set remove() and Set discard()

remove() discard()
Definition The remove() method removes the specified element from the set. The discard() method removes the specified element from the set if it is present.
Parameters This method takes one argument: the element to be removed. This method takes one argument: the element to be removed.
Behavior If the element is not found in the set, the remove() method raises a KeyError. If the element is not found in the set, discard() does nothing and does not raise an error.
Return Value This method does not return any value. It modifies the set in place. This method does not return any value. It modifies the set in place.

 

Leave a Comment

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