Python set Method - discard()

www.‮itfigi‬dea.com

The discard() method in Python is used to remove a specified element from a set if it is present. If the element is not present in the set, the method does nothing.

The syntax for the discard() method is as follows:

set.discard(element)

Here, set is the set from which we need to remove the element. If element is present in set, it is removed, otherwise the method does nothing.

Example:

# Creating a set
fruits = {'apple', 'banana', 'cherry', 'orange'}

# Removing an element from the set
fruits.discard('banana')

# Displaying the modified set
print(fruits)   # Output: {'apple', 'orange', 'cherry'}

In the above example, the discard() method is used to remove the element 'banana' from the fruits set. Since 'banana' is present in the set, it is removed and the output shows the modified set. If we try to remove an element that is not present in the set, the method does nothing:

# Trying to remove a non-existent element
fruits.discard('mango')

# Displaying the set
print(fruits)   # Output: {'apple', 'orange', 'cherry'}

In this case, since 'mango' is not present in the set, the discard() method does nothing and the output shows the original set.