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:
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'}Using update() Method:
The
update()method can add multiple elements to the set. You can pass a list, tuple, string, or another set to theupdate()method.fruits = {"apple", "banana", "cherry"} fruits.update(["elderberry", "fig", "grape"]) print(fruits) # Output: {'apple', 'banana', 'cherry', 'elderberry', 'fig', 'grape'}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'}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
Easy- Create a set named
my_setcontaining the following items:"apple","banana", and"cherry". - Use the
add()method to add the item"date"to the set. - Use the
update()method to add the items"elderberry"and"fig"to the set. - Use the
update()method with a list to add the items"grape"and"honeydew"to the set. - Print the final set
Try it yourself