Python Set remove():

The remove() method deletes an element from a set. It will generate a key error exception if the value is not present.

Method signature

The signature for the remove() method is as shown below. Here, s1 refers to a set from which we remove an element.

s1.remove(element)

Method parameters and return type

  • The remove() method takes a value to be deleted as a parameter.
  • However, it doesn’t return any value.

Python Set Discard Examples:

Example 1: In this example, let us take a set s1 with a set of numbers.

#Initializing the Set
s1 = {18,13,48,36,65}
#Printing a set
print("Before remove ",s1)
# Removing an element 13 from set
s1.remove(13)
#Printing a set
print("After remove ",s1)

Output

Before remove  {65, 36, 13, 48, 18}
After remove  {65, 36, 48, 18}

Example 2: In this case, let us consider a set that contains a list of programming languages offered by an educator. Thereafter, we remove say “C” from the list.

#Intializing the Set
p1 = {"Java", "Python", "C", "C++"}
#Printing a set
print("Programming languages offered ",p1)
# Removing a value
p1.remove("C")
# Printing a Set again
print("Now, Programming languages offered",p1)

Output

Programming languages offered  {"Java", "Python", "C", "C++"}
Now, Programming languages offered  {"Java", "Python", "C++"}

Example 3: In this example, let us demonstrate the remove() method on a mixed set. Here, we will remove the value that is not present in the list. An element “delhi” will not be removed just because python is case sensitive. So, “delhi” is different from “Delhi”. Rather, it will raise an keyerror Exception.

#Intializing the Set
c1 = {"Sam",25,88.5,"Delhi"}
# Printing a Set
print ("Before remove ",c1)
# Removing a value
c1.remove("delhi")
# Printing a Set
print ("After remove ",c1)

Output

Before remove  {88.5, 25, 'Delhi', 'Sam'}
Traceback (most recent call last):
  File "main.py", line 6, in 
    c1.remove("delhi")
KeyError: 'delhi'

Conclusion

The remove() method deletes an element from a set only if an element is present. Otherwise, it generates run time error, and the program terminates.

References

Happy Learning 🙂

Leave A Comment