Home »
Python
Python Set discard() Method with Example
Python Set discard() Method: Here, we are going to learn how to remove a given element from the set in Python?
Submitted by IncludeHelp, on November 27, 2019
Set discard() Method
discard() method is used to remove a given element from the set, it accepts an element and removes it from the set.
Note: If the given element does not exist in the set, the “discard() method” does not return any error.
Syntax:
set_name.discard(element)
Parameter(s):
- element – It represents the element/value to be removed from the list.
Return value:
The return type of this method is <class 'NoneType'>, it returns nothing.
Example 1:
# Python Set discard() Method with Example
# declaring the sets
cars_1 = {"Porsche", "Audi", "Lexus"}
cars_2 = {"Porsche", "Mazda", "Lincoln"}
# printing the sets before discard() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)
# removing an element from cars_1
cars_1.discard("Porsche")
# removing an element from cars_2
cars_2.discard("Lincoln")
# printing the sets after dLincoln() call
print("cars_1:", cars_1)
print("cars_2:", cars_2)
Output
cars_1: {'Audi', 'Lexus', 'Porsche'}
cars_2: {'Mazda', 'Porsche', 'Lincoln'}
cars_1: {'Audi', 'Lexus'}
cars_2: {'Mazda', 'Porsche'}
Example 2:
# Python Set discard() Method with Example
# declaring a set
cities = {"New Delhi", "Banglore", "Indore", "Gwalior"}
# printing set before discard() call
print("cities:", cities)
# removing "New Delhi" from the set
cities.discard("New Delhi")
# removing an element that does not exist
# in the set, thus we will remove "Mumbai"
# method discard() will not give any error
cities.discard("Mumbai")
# printing set after discard() call
print("cities:", cities)
Output
cities: {'New Delhi', 'Gwalior', 'Indore', 'Banglore'}
cities: {'Gwalior', 'Indore', 'Banglore'}
TOP Interview Coding Problems/Challenges