← Back to Chapters

Python Set Comprehension

? Python Set Comprehension

⚡ Quick Overview

Set comprehension is a compact way to create sets in Python using a single, readable expression. It replaces longer loops where you would manually add elements to a set, and automatically removes duplicates.

General pattern: {expression for item in iterable if condition}

? Key Concepts

  • Curly braces {} are used to define a set comprehension.
  • The expression before for decides what each element in the set will be.
  • The for part iterates over any iterable (list, tuple, string, range, etc.).
  • An optional if condition filters which elements are included.
  • Sets automatically remove duplicate values and do not preserve order.

? Syntax & Theory

Basic syntax:

{expression for item in iterable}

With condition:

{expression for item in iterable if condition}

The result is always a set object, which:

  • Contains only unique (non-duplicate) elements.
  • Is unordered (no guaranteed index-based access).
  • Only allows immutable types as elements (numbers, strings, tuples, etc.).

? Code Examples

? Creating a Set with Comprehension

Create a set of squares from 0 to 9 using a single line.

? View Code Example
# Set of squares from 0 to 9
squares = {x**2 for x in range(10)}
print(squares)  # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

? Using Conditionals in Set Comprehension

Filter elements while creating the set by adding an if condition. Here, we keep only even numbers.

? View Code Example
# Set of even numbers from 0 to 9
even_numbers = {x for x in range(10) if x % 2 == 0}
print(even_numbers)  # {0, 2, 4, 6, 8}

? Applying Functions or Expressions

You can apply a function or expression to each element while building the set. Below, we store the lengths of each word.

? View Code Example
words = ["apple", "banana", "cherry"]
lengths = {len(word) for word in words}
print(lengths)  # {5, 6}  (lengths of words)

♻️ Combining Comprehension with Other Iterables

Set comprehension works with any iterable. Here, we iterate over a string and collect unique uppercase letters.

? View Code Example
letters = {char.upper() for char in "hello world"}
print(letters)  # {'H', 'E', 'L', 'O', 'W', 'R', 'D'}

? Live Output & Explanation

? What’s Happening Behind the Scenes?

Example: {x**2 for x in range(5)}

The loop steps:

  1. x = 00**2 = 0 → add 0 to the set.
  2. x = 11**2 = 1 → add 1 to the set.
  3. x = 24 → add 4.
  4. x = 39 → add 9.
  5. x = 416 → add 16.

Final result is a set: {0, 1, 4, 9, 16}. Note that if two different x values produced the same square, the duplicate would automatically be removed by the set.

? Common Use Cases

  • Extracting unique values from a list in one line.
  • Filtering elements based on a condition (e.g., only even numbers, only positive values).
  • Transforming data while removing duplicates (e.g., lengths of strings, absolute values).
  • Quickly building lookup sets for membership tests like if x in my_set.

✅ Tips & Best Practices

  • Use set comprehension to make code shorter and more readable than manual loops.
  • Remember that sets automatically remove duplicate elements—no extra work needed.
  • Combine expressions and conditions to build powerful one-line transformations.
  • Always use curly braces {} for set comprehension; parentheses create a generator.
  • Use set comprehension when you care about uniqueness, not order.
  • Avoid putting mutable objects (like lists or other sets) inside sets—use tuples instead if needed.

? Try It Yourself

  • Create a set of cubes from 0 to 9 using set comprehension.
  • Modify it to include only odd cubes (use an if condition).
  • Given a list of words, build a set of their first letters using set comprehension.
  • Take a list with duplicate numbers and use set comprehension to build a set that automatically removes duplicates.
  • Experiment with strings: create a set of unique vowels used in a sentence.