There are two different ways to add elements to a set:
The
.add()
method can add a single element to theset
.# Create a set to hold the song tags song_tags = {'country', 'folk', 'acoustic'} # Add a new tag to the set and try to add a duplicate. song_tags.add('guitar') song_tags.add('country') print(song_tags)Would output:
{'country', 'acoustic', 'guitar', 'folk'}The
.update()
method can add multiple elements.# Create a set to hold the song tags song_tags = {'country', 'folk', 'acoustic'} # Add more tags using a hashable object (such as a list of elements) other_tags = ['live', 'blues', 'acoustic'] song_tags.update(other_tags) print(song_tags)Would output:
{'acoustic', 'folk', 'country', 'live', 'blues'}
There are a few things to note about adding to a set:
Neither of these methods will add a duplicate item to a
set
.A
frozenset
can not have any items added to it and so neither of these methods will work.Notice that when the elements are printed, they are not printed in the same order in which they entered the
set
. This is becauseset
andfrozenset
containers are unordered.
Let’s practice adding to a set!
Instructions
In our application, we have a section for upcoming artists to upload their own music. When uploading songs, the artists add their own tags, but other users can add tags to the songs later on.
For this version of the app, we are provided a song_data
dictionary as well as a few tags from users in the form of strings.
For the first step, create a new set
called tag_set
from the original song’s tags located in song_data
.
Next, add the three user tag strings to tag_set
.
Finally, update song_data
so that the value of the key, 'Retro Words'
is equal to the updated tag set
.