A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-remove-items-set/ below:

Remove items from Set - Python

Remove items from Set - Python

Last Updated : 19 Apr, 2025

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}.

Using remove()

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.

Python
a = {1, 2, 3, 4, 5}

a.remove(3)  
print(a) 

Explanation:

Using discard()

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.

Python
a = {1, 2, 3, 4, 5}

a.discard(3)
a.discard(6)  

print(a)  

Explanation:

Using pop()

pop() method removes and returns a random element from a set. Since sets are unordered element removed is arbitrary and may not be predictable.

Python
a = {1, 2, 3, 4, 5}
r = a.pop()
print(f"Removed: {r}")
print(a)  

Output
Removed: 1
{2, 3, 4, 5}

Explanation:

Using clear()

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.

Python
a = {1, 2, 3, 4, 5}
a.clear()  
print(a) 

Explanation: clear() method removes all elements from the set "a", leaving it empty.

Also read: remove(), discard(), clear(), pop(), set.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4