Home »
Python
Python Set remove() Method (with Examples)
Python Set remove() Method: In this tutorial, we will learn about the remove() method of the set class with its usage, syntax, parameters, return type, and examples.
By IncludeHelp Last updated : June 14, 2023
Python Set remove() Method
The remove() is an inbuilt method of the set class that is used to remove a specified element from the set. The method is called with this set, accepts an element, and removes it from the set if it exists, if the element does not exist in the set, the method returns an error.
Syntax
The following is the syntax of remove() method:
set_name.remove(element)
Parameter(s):
The following are the parameter(s):
- element – It represents the element to be removed from the list.
Return Value
The return type of this method is <class 'NoneType'>, it returns nothing.
Example 1: Use of Set remove() Method
# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
nums = {100, 200, 300, 400, 500}
# printing the sets before removing
print("Before the calling remove() method...")
print("cars: ", cars)
print("nums: ", nums)
# Removing the elements from the sets
cars.remove("Porsche")
cars.remove("Mazda")
nums.remove(100)
nums.remove(500)
# printing the sets after removing
print("After the calling remove() method...")
print("cars: ", cars)
print("nums: ", nums)
Output
Before the calling remove() method...
cars: {'Mazda', 'Audi', 'Porsche', 'Lexus', 'Lincoln'}
nums: {100, 200, 300, 400, 500}
After the calling remove() method...
cars: {'Audi', 'Lexus', 'Lincoln'}
nums: {200, 300, 400}
Example 2: Use of Set remove() Method
Demonstrating example, how method raises error if element is not find in the set?
# Python Set remove() Method
# declaring the sets
cars = {"Porsche", "Audi", "Lexus", "Mazda", "Lincoln"}
# printing the set
print("cars: ", cars)
# removing an item (which exists in the set)
cars.remove("Porsche")
# printing the set again
print("cars: ", cars)
# removing an item (which does not exist in the set)
# it will return an error
cars.remove("BMW")
Output
cars: {'Mazda', 'Audi', 'Lexus', 'Porsche', 'Lincoln'}
cars: {'Mazda', 'Audi', 'Lexus', 'Lincoln'}
Traceback (most recent call last):
File "main.py", line 15, in <module>
cars.remove("BMW")
KeyError: 'BMW'