What does the discard() method do in Python sets?
a) Removes an element from the set if it exists, without raising an error
b) Removes an element from the set and raises an error if it does not exist
c) Clears all elements from the set
d) Adds a new element to the set
Answer:
a) Removes an element from the set if it exists, without raising an error
Explanation:
The discard()
method in Python sets removes a specified element from the set if it exists. If the element is not found in the set, discard()
does nothing and does not raise an error. This makes discard()
a safe method to use when you are unsure if the element is present in the set.
# Example of discard() method
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
fruits.discard("grape") # grape is not in the set, no error raised
print(fruits) # Output: {'apple', 'cherry'}
In this example, “banana” is removed from the fruits
set using discard()
. When attempting to discard “grape,” which is not in the set, the method does nothing and no error is raised.
The discard()
method is useful for safely removing elements from a set without worrying about potential errors if the element is not found.