Python Basics — Set Comprehensions

1 minute read

Set Comprehensions

Just like list and dict comprehensions, Python supports set comprehensions for creating sets concisely.

Basic Syntax

{expression for item in iterable}
squares = {x ** 2 for x in range(6)}
print(squares)  # {0, 1, 4, 9, 16, 25}

Conditional Filtering

# Even squares only
even_squares = {x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares)  # {0, 4, 16, 36, 64}

Set Comprehension vs List Comprehension

The difference is the braces — {} instead of []:

# List comprehension — preserves duplicates and order
list_result = [len(w) for w in ["hi", "hello", "hey", "howdy"]]
print(list_result)  # [2, 5, 3, 5]

# Set comprehension — unique values only
set_result = {len(w) for w in ["hi", "hello", "hey", "howdy"]}
print(set_result)  # {2, 3, 5}

Deduplication Patterns

Unique Characters

text = "hello world"
unique_chars = {ch for ch in text if ch != " "}
print(unique_chars)  # {'h', 'e', 'l', 'o', 'w', 'r', 'd'}

Unique First Letters

words = ["apple", "avocado", "banana", "blueberry", "cherry"]
first_letters = {w[0] for w in words}
print(first_letters)  # {'a', 'b', 'c'}

Unique Domains from Emails

emails = [
    "alice@gmail.com",
    "bob@yahoo.com",
    "charlie@gmail.com",
    "diana@outlook.com",
    "eve@yahoo.com",
]

domains = {email.split("@")[1] for email in emails}
print(domains)
# {'gmail.com', 'yahoo.com', 'outlook.com'}

Performance Considerations

Set comprehensions are efficient for deduplication because sets use hash-based lookups:

import timeit

data = list(range(10000)) * 10  # 100,000 items with duplicates

# Set comprehension
set_time = timeit.timeit(lambda: {x for x in data}, number=100)

# List comprehension -> set
list_set_time = timeit.timeit(lambda: set([x for x in data]), number=100)

# Direct set conversion
direct_time = timeit.timeit(lambda: set(data), number=100)

print(f"Set comp:    {set_time:.4f}s")
print(f"List→set:    {list_set_time:.4f}s")
print(f"set(data):   {direct_time:.4f}s")  # Usually fastest

When you just need to deduplicate, set(iterable) is simplest. Use comprehensions when you need to transform elements.

Comparison Table

Feature List Comp Set Comp Dict Comp
Syntax [expr for ...] {expr for ...} {k: v for ...}
Duplicates Allowed Removed Last key wins
Ordered Yes No Insertion order
Indexed Yes No By key

Summary

  • {expr for item in iterable} creates a set
  • Duplicates are automatically removed
  • Use with if for conditional filtering
  • Prefer set(iterable) for simple deduplication
  • Use comprehensions when transforming elements

Next up: Sets — Practice Exercises →

Updated: