Learn

In Python, there are multiple ways to create a set. A set object can be created by passing an iterable object into its constructor, using curly braces, or using a set comprehension.

Let’s examine the sytnax of these methods:

# Creating a set with curly braces music_genres = {'country', 'punk', 'rap', 'techno', 'pop', 'latin'} # Creating a set from a list using set() music_genres_2 = set(['country', 'punk', 'rap', 'techno', 'pop', 'latin'])

It’s worth noting that creating a set from a list with duplicates produces a set with the duplicates removed. Here is an example:

# Creating a set with curly braces music_genres_3 = set(['country', 'punk', 'rap', 'pop', 'pop', 'pop']) print(music_genres_3)

Will output:

{'country', 'punk', 'pop', 'rap'}

While we use a similar data type in the sets above, sets can actually contain any combination of data types as long as they are unique values. Here is an example:

music_different = {70, 'music times', 'categories', True , 'country', 45.7}

We can also create an empty set with one specific method:

# Creating an empty set using the set() constructor # Doing set = {} will define a dictionary rather than a set. empty_genres = set()

Lastly, similar to list comprehensions, we can create sets using a set comprehension and a data set (such as a list). Here is an example:

items = ['country', 'punk', 'rap', 'techno', 'pop', 'latin'] music_genres = {category for category in items if category[0] == 'p'} print(music_genres)

Would output a set containing all elements from items starting with the letter 'p':

{'punk', 'pop'}

Now, let’s practice these methods to get a feel of how to create a set!

Instructions

1.

We have a great idea for an application that allows users to share music that they create with others.

One of the features of this application is the ability to tag songs with descriptive tags about the genre, mood, instruments, etc. Our team members have taken a survey of user’s favorite genres of music and provided us with a list of the results.

Unfortunately, it seems like there are some duplicates in the collection. For the first step, find all of the genres of music that the users submitted without duplicates by creating a set from genre_results.

Store the set in a variable called survey_genres. Finally, print survey_genres to see the new set!

2.

You want to test if it is plausible to use abbreviated tags for describing music.

For this step, use a set comprehension to create a new set called survey_abbreviated which stores the first three letters of each genre found in the survey results without duplication.

Print survey_abbreviated to see the result!

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?