Menu
Coddy logo textTech

Add Items

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

Sets are mutable, which means you can modify them after creation by adding new elements. Python provides several ways to add items to a set:

  1. Using add() Method:

    The add() method adds a single element to the set. If the element is already present, the set remains unchanged.

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

    The update() method can add multiple elements to the set. You can pass a list, tuple, string, or another set to the update() method.

    fruits = {"apple", "banana", "cherry"}
    fruits.update(["elderberry", "fig", "grape"])
    print(fruits)  # Output: {'apple', 'banana', 'cherry', 'elderberry', 'fig', 'grape'}
  3. Using update() with Different Iterables:

    The update() method can also accept other iterables like strings or sets.

    fruits = {"apple", "banana", "cherry"}
    fruits.update("date")  # Adds each character in "date"
    print(fruits)  # Output: {'apple', 'banana', 'cherry', 'd', 'a', 't', 'e'}
    
    fruits.update({"elderberry", "fig"})
    print(fruits)  # Output: {'apple', 'banana', 'cherry', 'elderberry', 'fig', 'd', 'a', 't', 'e'}
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
  1. Create a set named my_set containing the following items: "apple", "banana", and "cherry".
  2. Use the add() method to add the item "date" to the set.
  3. Use the update() method to add the items "elderberry" and "fig" to the set.
  4. Use the update() method with a list to add the items "grape" and "honeydew" to the set.
  5. Print the final set

Try it yourself

All lessons in Sets in Python