Today we’ll be talking about set comprehensions.
If you know how to use list comprehensions, it’ll be much easier for you to use all the other types of comprehensions, among which are set comprehensions, which are the topic of this article, so if you don’t feel comfortable about list comprehensions, I have an article about them, so feel free to read it first.
Set comprehensions are similar to list comprehensions, but they return sets. Instead of square brackets we use curly braces. We should use set comprehensions if we need unique elements, without any doubles. In our example we’ll first make a list comprehension and then a set comprehension, so that we can see the difference.
Let’s start by splitting a text and making a list of the words that make it up:
>>> text = "She sat in a big armchair with a big book in her big hands. "
>>> words = text.split()
>>> words
['She', 'sat', 'in', 'a', 'big', 'armchair', 'with', 'a', 'big', 'book', 'in', 'her', 'big', 'hands.']
Now, we want a list of all the words that contain the letter “b”. So, let’s make a list comprehension:
>>> b_words = [word for word in words if "b" in word]
>>> print(b_words)
['big', 'big', 'book', 'big']
That’s OK, but there are doubles. If we need unique elements, we need a set comprehension:
>>> b_words_set = {word for word in words if "b" in word}
>>> print(b_words_set)
{'book', 'big'}
It does the job well.
Here’s the video version of the article: