Menu Close

Python Set remove() Method

Python set remove

In this guide, we are going to learn all about the Python set remove() method along with examples. Python set remove() method is used to remove the specified item from the set.

In the previous tutorial, we have seen all about the Python set pop method to delete random items from the set.
I recommend, before going through this article, please check out our previous Python set tutorial.

Python set remove() method

remove function in Python is a set function that is used to remove a specified item from the set.
remove function is different from the discard() function because the remove() function raises an error if the specified element is not found but the discard is not.

Syntax

The syntax of the remove function in Python is:-

set.remove(item)

Parameter

Python set remove function accept one parameter:-

  • item – Required. item to be deleted from the set.

Return Value

The Python set remove method does not return any value it changes the the original Python set.

Python set remove() example

Example 1:

Remove “java” from set


my_set = { 'Python', 'Java', 'JavaScript', 'C++'}
print(my_set)
my_set.remove('Java')
print(my_set)

Output:


{'Java', 'Python', 'C++', 'Javascript'}
{'Python', 'C++', 'Javascript'}

Example 2:

You will get an error, If you try to delete an item that does not exist in the set.


my_set = { 'Python', 'Java', 'JavaScript', 'C++'}
print(my_set)
my_set.remove('HTML')
print(my_set)

Output

Traceback (most recent call last):
  File "./prog.py", line 3, in <module>
KeyError: 'HTML'

Note:- if the specified item does not exist in the set, the remove function will raise an error.

Conclusion

In this Python set method tutorial, you have learned all about the Python set remove method to delete the specified item from the Python set.
If the specified item does not exist in the set, the discard function will not raise any error.

I hope this article will help you, please keep visiting to continue for further Python methods.

Other set methods


For more information:- Click Here

Python Set issubset() Method
Python Set symmetric_difference() Method

Related Posts