Course Content
Python Data Structures
Python Data Structures
The update() Method
The update()
method in Python allows you to add multiple elements to a set at once. This method takes an iterable (like a list, tuple, or another set) and adds its elements to the existing set.
The update()
method can accept:
- Lists:
[movie1, movie2, ...]
; - Tuples:
(movie1, movie2, ...)
; - Other Sets:
{movie1, movie2, ...}
.
# Original set of favorite movies favorite_movies = {"Inception", "Interstellar", "Tenet"} # Adding multiple new movies favorite_movies.update(["Tenet", "Memento", "The Prestige"]) # Print the updated set print(favorite_movies)
Note
If any element being added already exists in the set, it will not be duplicated. The order of elements in a set is not guaranteed and may vary.
Swipe to start coding
You are given the set marvel_movies
and the tuple movies_to_add
.
Your goal:
- Add both movies from the tuple to the set.
- Use the
update()
method to accomplish this.
Solution
Thanks for your feedback!
The update() Method
The update()
method in Python allows you to add multiple elements to a set at once. This method takes an iterable (like a list, tuple, or another set) and adds its elements to the existing set.
The update()
method can accept:
- Lists:
[movie1, movie2, ...]
; - Tuples:
(movie1, movie2, ...)
; - Other Sets:
{movie1, movie2, ...}
.
# Original set of favorite movies favorite_movies = {"Inception", "Interstellar", "Tenet"} # Adding multiple new movies favorite_movies.update(["Tenet", "Memento", "The Prestige"]) # Print the updated set print(favorite_movies)
Note
If any element being added already exists in the set, it will not be duplicated. The order of elements in a set is not guaranteed and may vary.
Swipe to start coding
You are given the set marvel_movies
and the tuple movies_to_add
.
Your goal:
- Add both movies from the tuple to the set.
- Use the
update()
method to accomplish this.
Solution
Thanks for your feedback!