Menu Close

Python Set remove() Method

Python set remove

In this guide, we are going to learn all about 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 the 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 different from discard function because remove function raise an error if the specified element not found but discard not.

Syntax

The syntax of remove function in Python is:-

set.remove(item)

Parameter

Python set remove function accept one parameter:-

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

Return Value

The python set remove method in python does not return any value, if modify the original value.

Python set remove() exmaple

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 item that is not exist in 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