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}
{} are used to define a set comprehension.for decides what each element in the set will be.for part iterates over any iterable (list, tuple, string, range, etc.).if condition filters which elements are included.Basic syntax:
{expression for item in iterable}
With condition:
{expression for item in iterable if condition}
The result is always a set object, which:
Create a set of squares from 0 to 9 using a single line.
# 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}
Filter elements while creating the set by adding an if condition. Here, we keep only even numbers.
# 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}
You can apply a function or expression to each element while building the set. Below, we store the lengths of each word.
words = ["apple", "banana", "cherry"]
lengths = {len(word) for word in words}
print(lengths) # {5, 6} (lengths of words)
Set comprehension works with any iterable. Here, we iterate over a string and collect unique uppercase letters.
letters = {char.upper() for char in "hello world"}
print(letters) # {'H', 'E', 'L', 'O', 'W', 'R', 'D'}
Example: {x**2 for x in range(5)}
The loop steps:
x = 0 → 0**2 = 0 → add 0 to the set.x = 1 → 1**2 = 1 → add 1 to the set.x = 2 → 4 → add 4.x = 3 → 9 → add 9.x = 4 → 16 → 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.
if x in my_set.{} for set comprehension; parentheses create a generator.0 to 9 using set comprehension.if condition).