Python

Python Set Comprehension

Set comprehension provides a concise way to create a set from an iterable.

It is similar to list comprehension and dictionary comprehension, but the result is a set, which means:

  • Duplicate values are automatically removed.
  • Sets are unordered.
  • Set elements must be hashable.
  • It is useful for filtering and transforming unique data.

Basic Syntax

{expression for item in iterable}

For example:

numbers = [1, 2, 3, 4, 5]

squares = {
    x ** 2
    for x in numbers
}

print(squares)

Output:

{1, 4, 9, 16, 25}

 

The important difference is the type of brackets:

 

[x for x in numbers]       # List comprehension
{x for x in numbers}       # Set comprehension
{x: x for x in numbers}   # Dictionary comprehension

 

1. Basic Set Comprehension

 

numbers = [1, 2, 3, 4, 5]

result = {
    x
    for x in numbers
}

print(result)

 

Output:

{1, 2, 3, 4, 5}

 

This creates a set containing the numbers.

2. Remove Duplicate Values

One of the most useful applications of set comprehension is removing duplicates.

 

numbers = [1, 2, 2, 3, 3, 4, 5, 5]

unique_numbers = {
    x
    for x in numbers
}

print(unique_numbers)

 

Output:

{1, 2, 3, 4, 5}

 

The duplicate values are automatically removed.

3. Create Squares

 

numbers = [1, 2, 3, 4, 5]

squares = {
    x ** 2
    for x in numbers
}

print(squares)

 

Output:

{1, 4, 9, 16, 25}

4. Create Cubes

 

numbers = [1, 2, 3, 4, 5]

cubes = {
    x ** 3
    for x in numbers
}

print(cubes)

Output:

{1, 8, 27, 64, 125}

5. Double Every Number

numbers = [10, 20, 30, 40]

result = {
    x * 2
    for x in numbers
}

print(result)

Output:

{20, 40, 60, 80}

6. Set Comprehension with a Condition

Set comprehension can contain a if condition.

Syntax

 

{expression for item in iterable if condition}

 

Example:

 

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = {
    x
    for x in numbers
    if x % 2 == 0
}

print(even_numbers)

 

Output:

{2, 4, 6}

 

7. Get Odd Numbers

 

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

odd_numbers = {
    x
    for x in numbers
    if x % 2 != 0
}

print(odd_numbers)

 

Output:

{1, 3, 5, 7}

 

8. Get Numbers Greater Than 50

 

numbers = [20, 45, 60, 75, 30, 90]

result = {
    x
    for x in numbers
    if x > 50
}

print(result)

 

Output:

{60, 75, 90}

9. Get Positive Numbers

numbers = [-5, 10, -3, 20, 0, -8, 15]

positive_numbers = {
    x
    for x in numbers
    if x > 0
}

print(positive_numbers)

 

Output:

{10, 20, 15}

10. Get Negative Numbers

 

numbers = [-5, 10, -3, 20, 0, -8, 15]

negative_numbers = {
    x
    for x in numbers
    if x < 0
}

print(negative_numbers)

 

Output:

{-5, -3, -8}

11. Set Comprehension with Strings

Set comprehension works with strings because strings are iterable.

 

word = "Python"

characters = {
    char
    for char in word
}

print(characters)

 

Output:

{'P', 'y', 't', 'h', 'o', 'n'}

 

12. Remove Duplicate Characters

This is particularly useful with strings.

word = "banana"

unique_characters = {
    char
    for char in word
}

print(unique_characters)

 

Output:

{'b', 'a', 'n'}

 

The repeated a and n characters are automatically removed.

13. Get Unique Lowercase Characters

 

word = "Python Programming"

characters = {
    char.lower()
    for char in word
    if char.isalpha()
}

print(characters)

 

Output will contain the unique alphabetic characters from the string.

Because sets are unordered, the order may differ.

14. Set Comprehension with range()

 

numbers = {
    x
    for x in range(1, 11)
}

print(numbers)

 

Output:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

 

15. Even Numbers from range()

 

even_numbers = {
    x
    for x in range(1, 21)
    if x % 2 == 0
}

print(even_numbers)

 

Output:

{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

16. Squares of Even Numbers

We can combine transformation and filtering.

numbers = [1, 2, 3, 4, 5, 6]

result = {
    x ** 2
    for x in numbers
    if x % 2 == 0
}

print(result)

 

Output:

{4, 16, 36}

17. Convert Names to Uppercase

 

names = ["ram", "sita", "hari", "gita"]

result = {
    name.upper()
    for name in names
}

print(result)

 

Output:

{'RAM', 'SITA', 'HARI', 'GITA'}

18. Get Unique Name Initials

 

names = [
    "Ram",
    "Raj",
    "Sita",
    "Ramesh",
    "Hari"
]

initials = {
    name[0]
    for name in names
}

print(initials)

Output:

{'R', 'S', 'H'}

 

There are three names beginning with R, but only one R appears because the result is a set.

19. Filter Names by Length

names = ["Ram", "Sita", "Hari", "Raj", "Anita"]

result = {
    name
    for name in names
    if len(name) > 3
}

print(result)

 

Output:

{'Sita', 'Hari', 'Anita'}

20. Set Comprehension with if-else

Set comprehensions can also use conditional expressions.

 

numbers = [1, 2, 3, 4, 5]

result = {
    "Even" if x % 2 == 0 else "Odd"
    for x in numbers
}

print(result)

 

Output:

{'Even', 'Odd'}

 

Notice something important: although there are five numbers, the result contains only two values.

Why?

Because a set stores unique values only.

21. Practical Example : Student Grades

Suppose we have student marks:

 

marks = [75, 85, 90, 75, 85, 60]

 

We can get unique marks:

 

unique_marks = {
    mark
    for mark in marks
}

print(unique_marks)

 

Output:

{75, 85, 90, 60}

22. Get Unique Passing Marks

 

marks = [35, 40, 55, 60, 75, 40, 55, 80]

passing_marks = {
    mark
    for mark in marks
    if mark >= 40
}

print(passing_marks)

Output:

{40, 55, 60, 75, 80}

23. Practical Example : Product Categories

Suppose products belong to different categories:

products = [
    {"name": "Laptop", "category": "Electronics"},
    {"name": "Mouse", "category": "Electronics"},
    {"name": "Chair", "category": "Furniture"},
    {"name": "Table", "category": "Furniture"},
    {"name": "Book", "category": "Education"}
]

We can extract unique categories:

categories = {
    product["category"]
    for product in products
}

print(categories)

 

Output:

{'Electronics', 'Furniture', 'Education'}

 

This is a useful real-world application.

24. Practical Example : Unique Course Categories

 

courses = [
    {"name": "Python", "category": "Programming"},
    {"name": "Django", "category": "Programming"},
    {"name": "MERN", "category": "Web Development"},
    {"name": "Machine Learning", "category": "Data Science"},
    {"name": "Data Analysis", "category": "Data Science"}
]

categories = {
    course["category"]
    for course in courses
}

print(categories)

 

Output:

{'Programming', 'Web Development', 'Data Science'}

25. Practical Example : Unique Technologies

technologies = [
    "Python",
    "Django",
    "Python",
    "React",
    "Django",
    "JavaScript"
]

unique_technologies = {
    technology
    for technology in technologies
}

print(unique_technologies)

 

Output:

{'Python', 'Django', 'React', 'JavaScript'}

 

26. Set Comprehension vs List Comprehension

List Comprehension

 

numbers = [1, 2, 2, 3, 3, 4]

result = [
    x
    for x in numbers
]

print(result)

 

Output:

[1, 2, 2, 3, 3, 4]

 

Set Comprehension

 

numbers = [1, 2, 2, 3, 3, 4]

result = {
    x
    for x in numbers
}

print(result)

 

Output:

{1, 2, 3, 4}

 

The major difference is uniqueness.

27. Set Comprehension vs set()

Set comprehension:

 

numbers = [1, 2, 2, 3, 3, 4]

result = {
    x
    for x in numbers
}

print(result)

 

The same basic result can be obtained with:

 

numbers = [1, 2, 2, 3, 3, 4]

result = set(numbers)

print(result)

However, set comprehension becomes more useful when you need to transform or filter the values.

For example:

 

numbers = [1, 2, 3, 4, 5, 6]

result = {
    x ** 2
    for x in numbers
    if x % 2 == 0
}

print(result)

 

Output:

{4, 16, 36}

28. Set Comprehension with Nested Loops

Set comprehensions can contain multiple for clauses.

result = {
    x * y
    for x in [1, 2, 3]
    for y in [2, 4]
}

print(result)

 

Output:

{2, 4, 6, 8, 12}

 

Duplicate results are automatically removed.

29. Unique Word Lengths

words = [
    "Python",
    "Django",
    "React",
    "JavaScript",
    "SQL"
]

lengths = {
    len(word)
    for word in words
}

print(lengths)

Output:

{3, 4, 6, 10}

 

If multiple words have the same length, that length appears only once.

30. Practical Data Processing Example

Suppose we have customer locations:

 

customers = [
    {"name": "Ram", "city": "Butwal"},
    {"name": "Sita", "city": "Kathmandu"},
    {"name": "Hari", "city": "Butwal"},
    {"name": "Gita", "city": "Pokhara"},
    {"name": "John", "city": "Kathmandu"}
]

We can find all unique cities:

cities = {
    customer["city"]
    for customer in customers
}

print(cities)

 

Output:

{'Butwal', 'Kathmandu', 'Pokhara'}

 

This is a practical use of set comprehension for data processing.

31. Set Comprehension with a Function

Set comprehension can call functions.

 

def square(number):
    return number ** 2


numbers = [1, 2, 3, 4, 5]

result = {
    square(x)
    for x in numbers
}

print(result)

 

Output:

{1, 4, 9, 16, 25}

32. Set Comprehension with a Condition and Function

 

def square(number):
    return number ** 2


numbers = [1, 2, 3, 4, 5, 6]

result = {
    square(x)
    for x in numbers
    if x % 2 == 0
}

print(result)

 

Output:

{4, 16, 36}

Important Points to Remember

  1. Set comprehension creates a set.
  2. Basic syntax:

 

{expression for item in iterable}

 

  1. A condition can be added:

 

{expression for item in iterable if condition}

 

  1. Duplicate values are automatically removed.
  2. Sets are unordered, so you should not depend on their display order.
  3. Set elements must be hashable.
  4. Set comprehension is useful for extracting unique transformed or filtered values.
  5. You can use it with lists, tuples, strings, dictionaries, range(), and other iterables.

Easy Way to Remember

List Comprehension
[x for x in data]
→ Creates a LIST

Set Comprehension
{x for x in data}
→ Creates a SET with UNIQUE values

Dictionary Comprehension
{x: x for x in data}
→ Creates a DICTIONARY

 

Most Common Patterns

Create a set:

 

{x for x in numbers}

 

Transform values:

 

{x ** 2 for x in numbers}

 

Filter values:

 

{x for x in numbers if x % 2 == 0}

 

Transform + filter:

 

{x ** 2 for x in numbers if x % 2 == 0}

 

Extract unique values from structured data:

 

{item["category"] for item in items}
Interactive Sandbox
Python