Join Regular Classroom : Visit ClassroomTech

Python Set – remove() method

It is a method in python set that removes the specified element from the current set. If it doesn’t exist then it throws a KeyError Exception. It doesn’t return any value and modifies the given set.

Syntax:
set.remove(element)

Also Read: Python Set – add() method

Example 1:

# Python code to understand remove() method in set
# www.codewindow.in

s = {"amazing", "code", "best"}
s.remove("code")
print(s)

Output:

{'amazing', 'best'}

Explanation:
Here the element “code” has been removed from the parent set (s).

Example 2:

# Python code to understand remove() method in set
# www.codewindow.in

s = {5, 8, 4, 1, 5, 9}
s.remove(5)
print(s)

Output:

{1, 4, 8, 9}

Explanation:
Here the element “5” has been removed from the parent set (s).
Note: set doesnt allow duplicate element.

Example 3:

# Python code to understand remove() method in set
# www.codewindow.in

s = {5, 8, 4, 1, 5, 9}
s.remove(6)
print(s)

Output:

Traceback (most recent call last):
File "./prog.py", line 2, in
KeyError: 6

Explanation:
Here it throws an exception since the element is not present on the set. For this we use the method discard() which doesn’t throws an exception.


Follow Us

You Missed

Also Checkout