Python Set discard() Method with examples

Python Set discard

Now, we are going to learn about the discard method. Basically, this method is used to remove some elements from the set. We also have a remove method, which is also used to remove a specified element from the set. Soon, we would discuss what is different between the discard and the remove method.

So, if we need to remove some element from the set, we can simply make use of the discard method. We have to provide the element of the method, which we want to remove from the set. Let’s have a look at a simple program, which demonstrates the discard method.

Python Set discard() Method

As you can see, in the above program, we have a simple set, and then we are trying to discard element 4 from the set, and then we are trying to print the set. If you execute the program and observe the output, then you can simply find that the set now does not contain element 4. Let’s have a look at the output now

{1, 2, 3, 5}

As you can see in the output, element 4 has now been removed from the set. So, we can simply make use of the discard method, to remove some elements from the set.

We can simply say that the discard method removes an element if that element is there in the set. But what if the element is not a member of the set? Are we going to get errors just like we get with the remove method?

Well, when we are using the discard method to remove some element from the set, we provide such an element as an argument, which is not present in the set. So, in such a situation, we are not going to get into error.

Let’s have a look at a simple program, which tries to demonstrate the same thing.

As you can see in the above program, we are trying to remove element 40 from the set, and the element is not there in the set. But since we are using the discard method, we are not going to get an error and the set is left unchanged.

So, with this, we also understand the difference between the remove method and the discard method. If we are using the discard method to remove such an element, which is not there in the set, then we are not going to get an error.