Removing an element from a Set
In any data structure or data set, adding or removing the data is essential. Set is one of the most important data structures in Python. Set is an unordered collection of data and does not hold duplicate data, this makes it different from the other data structures like List and Tuple.
In this post, Let's take a look at couple of different ways of removing an element from a Set.
- Using 'remove()' method
- Using 'discard()' method
The purpose of both these methods is to remove an element (passed) from a set. So, What makes these methods different from each other? Read on to find out.
remove() method accepts an element to be removed as an argument and removes the corresponding element from the set.
One thing to note here is that the element passed as an argument to remove method must present in the set. If the element is not found in the set, this method returns KeyError.
In the above example, set doesn't contain the element '3' and we are passing '3' to the remove() method which results in KeyError.
So, we must handle this error when working with remove() method. This is useful if a specific action to be taken if the element is not found.
discard() method accepts an element to be removed as an argument and removes the corresponding element from the set.
As opposed to the remove() method, discard() method does not raise an exception if the element passed is not present in the set. This is useful when no specific action to be taken if the element we are trying to remove is not present in a set.
So, we need to choose whether to use remove() method or discard() method depending on what we need to do in case the element is not present in a set.
If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.