Python - Remove Items from a Set

Learn how to remove items from a set in Python using the remove() and discard() methods. Check out the example to see how the remove() method works to delete an item from a set.



Python - Remove Set Items

Remove Item

To remove an item in a set, use the remove() or the discard() method.

Example

thisset = {"orange", "grape", "mango"}

thisset.remove("grape")

print(thisset)
            
Output

{'orange', 'mango'}
            

Example

Remove an item using the discard() method:

Example

thisset = {"orange", "grape", "mango"}

thisset.discard("grape")

print(thisset)
            
Output

{'orange', 'mango'}
            

Example

Remove a random item using the pop() method:

Example

thisset = {"orange", "grape", "mango"}

x = thisset.pop()

print("Removed:", x)
print(thisset)
            
Output

Removed: mango
{'orange', 'grape'}
            

Example

Clear the set using the clear() method:

Example

thisset = {"orange", "grape", "mango"}

thisset.clear()

print(thisset)
            
Output

set()
            

Example

Delete the set using the del keyword:

Example

thisset = {"orange", "grape", "mango"}

del thisset

print(thisset)  # Raises an error because the set no longer exists