FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Set discard() method with examples




The discard() method in Python removes a specified element from the Set. It works same as remove() method, however there is a difference between remove() and discard() method. The remove() method raises an error when the specified element doesn't exist in the given set, however the discard() method doesn't raise any error if the specified element is not present in the set and the set remains unchanged.

Python Set discard() method syntax

set.discard(item)

Parameter: Here item is the element which we want to remove the set.
Return value: This method doesn't return anything.

Python Set discard() method example

In the following example we have a set of numbers and we are removing few elements from the given set using discard() method.

# A Set of numbers
numbers = {1, 2, 3, 4, 5}

# displaying the set before removing anything
print("Original Set is:", numbers)

# Element 3 & 4 are removed from the Set
numbers.discard(3)
numbers.discard(4)

# displaying the set after discard() method
print("Updated Set is:", numbers)

If element doesn't exist in the Set

If the specified element does not exist in the given Set then this method doesn't raise any error and the set remains unchanged. Lets take an example to see this in action.

# A Set of numbers
numbers = {1, 2, 3, 4, 5}

# displaying the set before removing anything
print("Original Set is:", numbers)

# trying to remove the element 99 from the set
numbers.discard(99)

# displaying the set after discard() method
print("Updated Set is:", numbers)

As you can see in the output that no errors were raised and the set remained unchanged when we tried to remove an element from the set which was not present. If you want the error to be raised in such cases then use the remove() method instead.







Leave Comment