FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Set remove() Method with examples




The remove() method in Python searches for the specified element in the given Set and removes it. If the specified element does not exist in the Set then an error is raised.

Python Set remove() method syntax

set.remove(item)

Parameter: Here item is the element which we want to remove the set.
Return value: This method doesn't return anything.

Python Set remove() method example

In the following example we have a Set of names and we are removing an element from this given set using the remove() method.

# A Set of names
names = {"Rick", "Negan", "Glenn"}

# Original Set
print("Original Set is:", names)

# Element "Negan" is removed from the Set
names.remove("Negan")

# Set after removing an element from it
print("Updated Set is:", names)

When element doesn't exist in the Set

If you try to remove an element from the Set which doesn't exist then an error is raised. Lets take an example to see this behaviour of remove() method.

Here we are trying to remove a name "noida" from the given set of names but the element does not exist in the set names, thus an error is raised as shown in the output below.

# A Set of names
names = {"Rick", "Negan", "Glenn"}

# Original Set
print("Original Set is:", names)

# Trying to remove element "Chaitanya"
names.remove("Chaitanya")

# Set after removing an element from it
print("Updated Set is:", names)

Output:

 
Original Set is: {'Glenn', 'Negan', 'Rick'}
Traceback (most recent call last):
  File "/Users/noida/PycharmProjects/noidaProJ/venv1/noidaDemo.py", 
line 8, in 
    names.remove("noida")
KeyError: 'noida'

Process finished with exit code 1

As you can see a KeyError is raised when we tried to remove an element from the set which was not present. If you do not want any error to be raised in such cases then use discard() method instead.







Leave Comment