Python Set remove
Now, we are going to learn about the remove method. As the name suggests, with the help of the remove method, we can simply remove the specified element from the set. Let’s have a look at a simple program, which demonstrates the remove method.
Python Set remove() Method
As you can see in the above program, we have a simple set, and then we are trying to remove the element True from the set. After that, we are trying to print the set. If you try to execute the program and observe the output, you can simply see that the True element is removed from the set. The output of the program looks something like this –
{‘GyaniPandit’, 3.1, ‘Python’, 29}
As you can see, the element True was removed from the set. The thing is that the element that we are providing to the remove method, should be a member of the set, or else we would get an error. Have a look at the below program, which demonstrates the same thing.
As you can see in the above program, we are trying to remove an element, which is not even part of the set. In such a situation, we get a KeyError. If we want to avoid this error, we can make use of the discard method. So, we can make use of the remove method, as and when required in our python program.