Python Set Discard():
The discard() method removes an element from a set only if that element is present in the set. However, It will not raise any exception if an element is not found.
Method signature
The signature for the discard() method is as shown below. In this case, s1 refers to a set from which an element is to be removed.
s1.discard(element)
Method parameters and return type
- The value to be deleted is passed as a parameter to discard() method.
- However, it doesn’t return any value.
Python Set Discard Examples:
Example 1: In this example, let us take a set s1 with set of numbers.
#Initializing the Set
s1 = {18,13,48,36,65}
#Printing a set
print("Before Discard ",s1)
# Removing an element 36 from set
s1.discard(36)
#Printing a set
print("After Discard ",s1)
Output
Before Discard {65, 36, 13, 48, 18}
After Discard {65, 13, 48, 18}
Example 2: In this example, let us consider a set that contains cities which salesman “sales1” is required to visit. As soon as sales1 visits a city, he discards it from his list.
#Intializing the Set
sales1 = {"Mumbai", "Pune", "Hyderabad", "Chennai"}
#Printing a set
print("Salesman will visit ",sales1)
# Removing a value
sales1.discard("Pune")
# Printing a Set again
print("Now, salesman will visit only",sales1)
Output
Salesman will visit {'Chennai', 'Hyderabad', 'Pune', 'Mumbai'}
Now, salesman will visit only {'Chennai', 'Hyderabad', 'Mumbai'}
Example 3: In this example, let us demonstrate the discard() method on a mixed set. Here, we will remove the value that is not present in the list. An element “delhi” is not removed just because python is case sensitive. Hence, “delhi” is different from “Delhi”
#Intializing the Set
c1 = {"Sam",25,88.5,"Delhi"}
# Printing a Set
print ("Before Discard ",c1)
# Removing a value
c1.discard("delhi")
# Printing a Set
print ("After Discard ",c1)
Output
Before Discard {88.5, 25, 'Sam', 'Delhi'}
After Discard {88.5, 25, 'Sam', 'Delhi'}
Conclusion
The discard() method removes an element from a set without generating any exceptions if an element is not found.
References
Happy Learning 🙂