Remove Set Items

 

What You'll Learn: In this tutorial, you'll discover how to remove items from a set using different methods. Sets are useful for storing unique items, and sometimes you need to remove elements from them.

Remove a Specific Item

To remove a specific item from a set, you can use the remove() or discard() method.

Using remove() Method:

python
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

Output: {'apple', 'cherry'}
 

Note: If the item to remove does not exist, remove() will raise an error.

Using discard() Method:

python
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

Output: {'apple', 'cherry'}
 

Note: If the item to remove does not exist, discard() will NOT raise an error.

Remove a Random Item

You can also use the pop() method to remove an item, but this method will remove a random item. The return value of the pop() method is the removed item.

Using pop() Method:

python
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

Output: 

cherry
{'apple', 'banana'}

Note: Since sets are unordered, you do not know which item will be removed.

Clear the Set

To empty the entire set, use the clear() method.

Using clear() Method:

python
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

Output: set()
 

Delete the Set

To delete the set completely, use the del keyword.

Using del Keyword:

python
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

Output: This will raise an error because the set no longer exists

Try It Yourself: Fun Exercises

  1. Remove a Fruit:
    • Create a set of fruits.
    • Remove a specific fruit using remove() and discard() methods.
  2. Random Removal:
    • Write a set of different items.
    • Use the pop() method to remove a random item and see the result.

Summary:

In this Python tutorial, we learned how to remove items from a set using the remove(), discard(), and pop() methods. We also explored how to clear a set with clear() and delete a set with del. These methods help you manage and update your sets efficiently. Keep experimenting and have fun with sets in Python!