Set Comprehensions
In this tutorial, we'll build unique collections from existing data.
A set comprehension builds a set from existing values.
words = ["apple", "banana", "apple"]
first_letters = {word[0] for word in words}
Output might be:
{"a", "b"}
The duplicate "a" appears only once because sets store unique values.
The Shape
{expression for item in collection}
This looks similar to a dictionary comprehension, but there is no key: value pair.
Removing Duplicates
Set comprehensions are useful when you want unique transformed values:
names = ["ada", "Ada", "GRACE", "grace"]
normalised = {name.lower() for name in names}
Output:
{"ada", "grace"}
Filtering
numbers = [1, 2, 2, 3, 4, 4]
even_numbers = {number for number in numbers if number % 2 == 0}
Output:
{2, 4}
Set or List?
Use a set comprehension when uniqueness matters. Use a list comprehension when order and duplicates matter.
letters_list = [word[0] for word in words]
letters_set = {word[0] for word in words}
The list may contain repeated letters. The set keeps each letter once.
Practice
Start with a list of email addresses. Use a set comprehension to collect the unique domain names after the @ symbol.