Menu
Coddy logo textTech

Remove Items

Lesson 5 of 11 in Coddy's Sets in Python course.

Python provides several methods to remove elements from a set, each with its own characteristics and use cases:

  1. Using remove() Method:

    The remove() method removes a specified element from the set. If the element is not found, it raises a KeyError.

    fruits = {"apple", "banana", "cherry"}
    fruits.remove("banana")
    print(fruits)  # Output: {'apple', 'cherry'}
  2. Using discard() Method:

    The discard() method also removes a specified element from the set, but it does not raise an error if the element is not found.

    fruits = {"apple", "banana", "cherry"}
    fruits.discard("banana")
    print(fruits)  # Output: {'apple', 'cherry'}
    
    fruits.discard("date")  # No error raised
    print(fruits)  # Output: {'apple', 'cherry'}
  3. Using pop() Method:

    The pop() method removes and returns an arbitrary element from the set. Since sets are unordered, you do not know which element will be removed. If the set is empty, it raises a KeyError.

    fruits = {"apple", "banana", "cherry"}
    item = fruits.pop()
    print(item)    # Output: (one of the elements, e.g., 'apple')
    print(fruits)  # Output: (the set without the popped element, e.g., {'banana', 'cherry'})
  4. Using clear() Method:

    The clear() method removes all elements from the set, resulting in an empty set.

    fruits = {"apple", "banana", "cherry"}
    fruits.clear()
    print(fruits)  # Output: set()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Write a function named remove_item that gets a set and an item and removes this item from the set, if it  does not exist, don't raise an error.

Try it yourself

def remove_item(s, item):
    # Write code here

All lessons in Sets in Python