![]() |
VOOZH | about |
We are given a set and our task is to remove specific items from the given set. For example, if we have a = {1, 2, 3, 4, 5} and need to remove 3, the resultant set should be {1, 2, 4, 5}.
remove() method in Python is used to remove a specific item from a set. If the item is not present it raises a KeyError so it's important to ensure item exists before using it.
{1, 2, 4, 5}
Explanation:
discard() method in Python removes a specified element from a set without raising a KeyError even if element does not exist in set. It's a safer alternative to remove() as it doesn't cause an error when element is missing.
{1, 2, 4, 5}
Explanation:
pop() method removes and returns a random element from a set. Since sets are unordered element removed is arbitrary and may not be predictable.
Removed: 1
{2, 3, 4, 5}
Explanation:
clear() method removes all elements from a set effectively making it an empty set. It does not return any value and directly modifies original set.