Set Comprehension
Set comprehension provides a concise way to create sets, similar to list comprehension but using curly braces {} instead of square brackets []. Sets automatically remove duplicates.
Basic Syntax
The general form of set comprehension is:
{expression for var in iter [if condition][...set comp]}Where:
expressionis the value to include in the setvaris the variable that iterates over the iterableiteris the iterable (list, range, etc.)if conditionis optional - filters elements- Additional set comprehensions are optional - for nested iterations
Simple Set Comprehension
The simplest form creates a set by applying an expression to each element:
s1 = {n * 2 for n in range(3)}print(s1) # {0, 2, 4}This is equivalent to:
s1 = set()for n in range(3): s1.add(n * 2)Set Comprehension with Condition
You can add a condition to filter elements:
s2 = {n * 2 for n in range(3) if n > 0}print(s2) # {2, 4}This only includes elements where n > 0, so it skips n = 0.
Copying a Set
You can use set comprehension to create a copy of a set:
s1 = {0, 2, 4}s3 = {n for n in s1}print(s3) # {0, 2, 4}Nested Set Comprehension
You can use multiple for clauses to create nested iterations:
s1 = {0, 2, 4}s2 = {2, 4}s4 = {(m, n) for m in s1 for n in s2}print(s4) # {(0, 2), (0, 4), (2, 2), (2, 4), (4, 2), (4, 4)}This creates all combinations of elements from s1 and s2 as tuples.
Multiple Conditions
You can have multiple conditions and multiple loops:
s5 = {m + n for m in range(-4, 4) if m % 2 == 0 for n in range(-4, 4) if n % 2 == 1}print(s5) # {-7, -5, -3, -1, 1, 3, 5}Note that sets automatically remove duplicates, so even though the list comprehension version had duplicates, the set version only contains unique values.
Exercises
Exercise 1: Basic Set Comprehension
Use set comprehension to create a set of squares of numbers from 0 to 9.
Basic Set Comprehension
squares = {n * n for n in range(10)}print(squares)Exercise 2: Set Comprehension with Condition
Use set comprehension to create a set of even numbers from 0 to 20.
Set Comprehension with Condition
evens = {n for n in range(21) if n % 2 == 0}print(evens)Exercise 3: Removing Duplicates
Given a list of numbers that may contain duplicates, use set comprehension to create a set of unique even numbers.
Removing Duplicates
n = int(input())numbers = []for i in range(n): numbers.append(int(input()))
unique_evens = {num for num in numbers if num % 2 == 0}print(unique_evens)Exercise 4: Nested Set Comprehension
Use nested set comprehension to create a set of all sums (i + j) where i is from 0 to 2 and j is from 0 to 2.
Nested Set Comprehension
sums = {i + j for i in range(3) for j in range(3)}print(sums)Exercise 5: Multiple Conditions
Use set comprehension to create a set of numbers from 1 to 50 that are divisible by both 3 and 5.
Multiple Conditions
numbers = {n for n in range(1, 51) if n % 3 == 0 and n % 5 == 0}print(numbers)