Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
The add() Method | Set
Python Data Structures
course content

Course Content

Python Data Structures

Python Data Structures

1. List
2. Dictionary
3. Tuple
4. Set

book
The add() Method

You can also add elements to a set. To do this, there's a specific add() method. It's important to note that with this method, you can add only one element at a time. So, if you want to add 4 elements, for example, you'll need to use this method 4 times. Let's check out an example.

1234567891011
# Creating an empty set favorite_movies = set() print("Initial set:", favorite_movies) # Output - Initial set: set() # Adding movies to the set favorite_movies.add("Inception") favorite_movies.add("Interstellar") favorite_movies.add("Tenet") favorite_movies.add("Dunkirk") print("Updated set:", favorite_movies) # Output - Updated set: {'Interstellar', 'Dunkirk', 'Inception', 'Tenet'}
copy

The add() method is best used for adding single elements.

Task
test

Swipe to show code editor

You want to add a new movie to your favorite_movies set. Use the add() method to add "Dunkirk" and "Tenet" to the set. Print the updated set.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 2
toggle bottom row

book
The add() Method

You can also add elements to a set. To do this, there's a specific add() method. It's important to note that with this method, you can add only one element at a time. So, if you want to add 4 elements, for example, you'll need to use this method 4 times. Let's check out an example.

1234567891011
# Creating an empty set favorite_movies = set() print("Initial set:", favorite_movies) # Output - Initial set: set() # Adding movies to the set favorite_movies.add("Inception") favorite_movies.add("Interstellar") favorite_movies.add("Tenet") favorite_movies.add("Dunkirk") print("Updated set:", favorite_movies) # Output - Updated set: {'Interstellar', 'Dunkirk', 'Inception', 'Tenet'}
copy

The add() method is best used for adding single elements.

Task
test

Swipe to show code editor

You want to add a new movie to your favorite_movies set. Use the add() method to add "Dunkirk" and "Tenet" to the set. Print the updated set.

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 2
Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
We're sorry to hear that something went wrong. What happened?
some-alt