Skip to main content

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
Submitted by devanshi.srivastava on June 20, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.