AppDividend
Latest Code Tutorials

Python Set remove() Method Example

0

Python Set remove() is an inbuilt function that is used to remove any specified element from a set. The remove() method removes the element that is present in the set. The difference between discard() and remove() method is, in discard() method, if the element is not present in the set, it does not throw any exception, wherein remove() method if the element is not present in the set, it throws an exception.

Python Set remove() Method

Python set remove() method searches for the given element in the set and removes it.

Syntax

set.remove(element)

Here the element is the argument that we want to remove from the set.

Return Value

The set remove() method does not return any value; it just returns None. But if the element is not present in the set, then the KeyError exception is thrown.

See the following programming example.

# app.py

# creating a set of even numbers till 10
evens = {2, 4, 6, 8, 10}
# Printing the set
print("The set is: ", evens)

# Now we will discard 8 from the set
evens.remove(6)

# Printing new set
print("New set is: ", evens)

# Asking user to enter the value
# which to be discarded
x = int(input("Enter number which you want to remove: "))
# discarding the value
evens.remove(x)
# printing the new set
print("Now new set is: ", evens)

Output

The set is:  {2, 4, 6, 8, 10}
New set is:  {2, 4, 8, 10}
Enter number which you want to remove: 16
Traceback (most recent call last):
  File "remove.py", line 16, in <module>
	evens.remove(x)
KeyError: 16

In this example, we have created the set of even numbers until 10. Then we have removed 6 from the set and see what the result is.

Then we have asked the user to give input on which number he/she wants to discard, and then we have called remove() function. But the user entered 16 as input, which is not present in the set, so the program threw a KeyError exception.

If you try to remove an element from the Set which doesn’t exist, then an error is raised. Let’s take the example to see this behavior of remove() method.

Finally, Python Set remove() Method Example is over.

See also

Python set pop()

Python set issuperset()

Python set issubset()

Python set isdisjoint()

Python set intersection_update()

Python set intersection()

Python set discard()

Python set difference_update()

Python set difference()

Python set copy()

Python set clear()

Python set add()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.