Home » Python

Python Set remove() Method with Example

Python Set remove() Method: Here, we are going to learn how to remove a specified element from the set in Python?
Submitted by IncludeHelp, on November 30, 2019

Set remove() Method

remove() method is used to remove a specified element from the set, the method accepts an element and removes from the set if it exists, if the element does not exist in the set, the method returns an error.

Syntax:

    set_name.remove(element)

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:

# Python Set remove() Method with Example

# 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}

Demonstrating example, how method raises error if element is not find in the set?

Example 2:

# Python Set remove() Method with Example

# 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'






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.