Skip to main content

Remove Item

Two methods take a specific item out of a set: remove() and discard().

Note: They differ when the item is missing. In that case, remove() raises an error.

Note: discard(), on the other hand, does NOT raise an error when the item is missing.

There is also the pop() method, but it picks the item for you, and you have no way of knowing which one it will choose.

Whatever it picks comes back as the return value of pop().

Note: Since sets are unordered, the item pop() takes out can't be predicted.

Example

Take "banana" out with remove():

Prompt
Create a set with "apple", "banana", and "cherry". Remove "banana" using the remove() method and print the set.
Output: complete Python program

Example

Take "banana" out with discard():

Prompt
Create a set with "apple", "banana", and "cherry". Remove "banana" using the discard() method and print the set.
Output: complete Python program

Example

Let pop() take out an arbitrary item:

Prompt
Create a set with "apple", "banana", and "cherry". Use the pop() method to remove a random item, print the removed item, then print the set.
Output: complete Python program

Example

Use clear() to leave the set empty:

Prompt
Create a set with "apple", "banana", and "cherry". Use the clear() method to empty the set and print the result.
Output: complete Python program

Example

With the del keyword, the whole set disappears:

Prompt
Create a set with "apple", "banana", and "cherry". Use the del keyword to delete the set completely, then try to print it to show the error.
Output: complete Python program