Skip to main content

4.0 Python: Remove Set Items

4.1 Remove Item​

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

4.1.1 Example​

Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)
note

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

4.1.2 Example​

Remove "banana" by using the discard() method:

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)
note

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

You can also use the pop() method to remove an item, but this method will remove a random item, so you cannot be sure what item that gets removed.

The return value of the pop() method is the removed item.

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)
note

Sets are unordered, so when using the pop() method, you do not know which item that gets removed.

4.1.3 Example​

The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)

4.1.4 Example​

The del() keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)