Skip to content
Home » Set Comprehensions in Python

Set Comprehensions in Python

Spread the love

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.

set comprehensions

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love
Tags:

Leave a Reply