Set Comprehension in Python 3 for Beginners

Josh Robin
May 6, 2019 · 4 min read

Coding in Python can be made a lot easier with list comprehension, and this is why it is widely used in the Python community. Less popular but still fairly common is the dictionary comprehension, which works in a similar way, but there is another tool in the realm of Python comprehensions that is almost never talked about, and that is set comprehension. As you might have guessed, this is similar to other types of Python comprehensions but for modifying and generating sets. Here are the basics of what you need to know about them.

How it Works

The key aspect of set comprehension that makes it unique is that it returns a set, which means the elements inside will be unordered and cannot contain any duplicates. The rest is pretty much the same as a list comprehension. The input can be anything that contains a group of elements.

Let’s look at some examples. What if I have some text and I want to pull out all the unique words in the form of a set?

In order for this to work properly, I will make sentence entirely lowercase and then remove the comma and the period. This can be done with the lower() and replace() functions. Then I can use the split() function to separate it into a list of words, and from there generate a set of all the unique words:

This is what our unique_words set will now look like:

As you can see, the original order of the words as they appeared in the sentence was not maintained in the result. In this case, it spits them out in alphabetical order, however, this is not necessarily going to happen every time. When thinking about a set, the order doesn’t actually matter. What’s important is that the words that appeared multiple times in the sentence (“the” and “thing”) now only appear once in the set.

Conditionals Within Set Comprehensions

To expand on the above example, what if I wanted to filter out any of the words that have more than three letters? Here’s how I would do that:

Output:

Just to show that we can, let’s return all the unique words again, but this time capitalize the ones that start with the letter “h” and leave the rest the same:

Output:

We can even do both of the above examples together in one set comprehension:

Output:

Nested Set Comprehensions

As with list and dictionary comprehensions, you can nest one set comprehension within another, although there is one very important caveat. In general with Python, when it comes to sets inside sets, the inner sets have to be frozen sets, or you will get an error. A frozen set is just like a set, although sets are mutable and frozen sets are not. The reason we need to do this is that mutable objects cannot be accessed with hash-based memory lookups, which is required for a set to function properly. In other words, sets are mutable, which makes them unhashable, and therefore they cannot exist as elements within a larger set unless they are frozen. Fortunately, we can easily make sets into frozen sets by wrapping them in the frozenset() function.

Let’s use the same sentence from before, but this time we will also iterate through each of the letters in each word and return only the consonants as a frozen set of unique letters.

Now consonants will be a set of frozen sets looking like this:

This is probably the most glaring distinction to make about set comprehension. Keep in mind that this only applies to a set within another set. Sets within lists, or within dictionaries, do not require frozen sets.

This pretty much covers the unique aspects of set comprehension. The rest pretty much follows the same basic rules of Python comprehension, so with that, you should have what you need to be able to explore all kinds of applications for this tool.

Enjoy!

The Startup

Get smarter at building your thing. Join The Startup’s +789K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Josh Robin

Written by

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +789K followers.

Josh Robin

Written by

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +789K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store