Learn

There are two different ways to add elements to a set:

  1. The .add() method can add a single element to the set.

    # 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'}
  2. 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 because set and frozenset containers are unordered.

Let’s practice adding to a set!

Instructions

1.

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.

2.

Next, add the three user tag strings to tag_set.

3.

Finally, update song_data so that the value of the key, 'Retro Words' is equal to the updated tag set.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?