Python: Removing Items from Set

We can remove items from set by using following methods:

By using remove() method

Elements can be removed from a set by using built-in remove() function.

set_1 = set(['apple','banana','cherry','pineapple'])
print("Initial Set:",set_1)
set_1.remove('cherry')
set_1.remove('pineapple')
print("Final Set:",set_1)

Output:

Initial Set: {'banana', 'apple', 'pineapple', 'cherry'}
Final Set: {'banana', 'apple'}

Note: If the element does not exist in the set then there will be a KeyError .To remove elements from a set without KeyError, use discard().

By using discard() method: 

It is used to remove elements from a set. It is also a built-in function. If the element doesn’t exist in the set, it remains unchanged.

set_1 = set(['apple','banana','cherry','pineapple'])
set_1.discard('apple')
print(set_1)

Output: {'banana', 'pineapple', 'cherry'}

By using clear method()

To remove all the elements from the set, clear() function is used.

set_1 = set(['apple','banana','cherry','pineapple'])
set_1.clear()
print(set_1)

Output: set()

Tags