Set Comprehension in Python with Example

In addition to well-known list comprehension, Python also supports set comprehension. It is a short-hand way of creating a set from an existing iterable, such as a list or a tuple. It was introduced in the Python 3.0 version.

Set comprehension in Python allows us to create a new set from an iterable object which will satisfy the specified condition. It applies conditions and transformations to elements of the iterable object while creating the set.

This powerful feature of Python enables us to write compact and expressive code. The most important characteristic of set comprehension is that elements are unique (i.e. no duplicate elements) in the returned set. However, elements in the returned set are unordered. Therefore, set comprehension is considerably faster.

Syntax for Set Comprehension in Python


Set comprehension has exactly the same structure as a list comprehension, except enclose it in curly braces ({ }) rather than square brackets ([ ]). It contains an expression and a loop with an optional condition enclosed in curly braces.

Like list comprehension, set comprehension also supports two syntaxes:

new_set = {expression for itr_var in iterable}
new_set = {expression for itr_var in iterable if condition}

In the above syntaxes,

  • The expression represents the transformation or computation to be performed on each element.
  • itr_var is the variable that takes the values from the iterable object.
  • The iterable is the source of data from which the set is constructed.
  • The if condition is an optional filter that determines whether an element should be included in the set (providing the order does not matter). Forgetting to include a condition may lead to unexpected results or incorrect outputs.

Note that there can be only 1 or multiple for loop statements, and 0 or multiple if statements.

Examples of Set Comprehension


Let’s look at some examples to better understand set comprehension.

Example 1: Squares of numbers

Suppose we want to create a set containing the squares of numbers from 1 to 6. We can use set comprehension as follows:

# Python program to create a set containing square of all numbers from 1 to 6.
squares = {x**2 for x in range(1, 7)}
print(squares)
Output:
       {1, 4, 36, 9, 16, 25}

In this example, x ** 2 is the output expression, range(1, 7) is the input sequence, x is the iterating variable representing the member of the input sequence.


The range(1, 7) function returns a list of six natural numbers starting from 1 and going up to but not including the number we pass it. So, in this case, the range(1, 7) function generates a list of numbers from 1 to 6.

The for loop statement iterates over each number of the sequence and passed to the output expression. The expression squares each number. The resulting values of the expression create a new set that we have stored in a variable named squares. As you see in the output of this code, set has not maintained the order.

The above code is equivalent to:

# Code without set comprehension.
# Creating a set object using set() function.
squares = set()
for x in range(1, 7):
    squares.add(x ** 2)
print(squares)

In this code, we have not used set comprehension. We have initially created an empty set object and added the square of numbers to the empty set one by one. With set comprehension, we have achieved the same result of the code in only one line.

Example 2: Removing duplicate elements

# Python program to remove duplicate elements from the list using set comprehension.
# Creating a list of elements.
my_list = [1, 2, 1, 5, 6, 5, 7, 8, 3, 2, 3, 4]

# Removing the duplicate elements from list with set comprehension.
my_set = {x for x in my_list}
print(my_set)
Output:
       {1, 2, 3, 4, 5, 6, 7, 8}

Let us rewrite this code using normal set.

# Creating a list of elements.
my_list = [1, 2, 1, 5, 6, 5, 7, 8, 3, 2, 3, 4]

# Creating a set object and pass my_list to its set function.
my_set = set(my_list)
print(my_set)


Example 3:

word = "Programming"
my_set = {c for c in word}
print(my_set)
Output:
       {'o', 'r', 'n', 'i', 'P', 'm', 'a', 'g'}

Set Comprehension with for loop and if statement


Example 4: Filtering odd numbers

Consider a list of numbers in which we will create a set containing only the odd numbers. We will use set comprehension with if condition to achieve this:

# Python program to obtain odd numbers from the list using set comprehension.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_numbers = {x for x in nums if x % 2 != 0}
print(odd_numbers)
Output:
       {1, 3, 5, 7, 9}

This set comprehension code is equivalent to the following code:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_set = set()
for x in nums:
    if x % 2 != 0:
        my_set.add(x)
print(my_set)

Set Comprehension with for loop and Nested if statements


Let’s look at a program in which we will find all numbers between 1 to 30 divisible by 2 and 5.

Example 5:

nums = {x for x in range(1, 31) if x % 2 == 0 if x % 5 == 0}
print(nums)
Output:
       {10, 20, 30}

Advantages of Set Comprehension


Set comprehension in Python provides several advantages that make it a useful technique in the Python programming language. Let’s look at some advantages of using it.

  • Set comprehension enables us to write concise and more readable code to perform complicated operations by reducing the number of lines of code.
  • It provides efficient and faster execution by using the optimized implementation of set operations in Python.
  • As a set only contains unique elements (no duplicate elements), set comprehension automatically erases duplicate values, simplifying data processing.

Limitations of Set Comprehension


While set comprehension is a powerful feature, it may not be suitable for all scenarios. Let’s look at some limitations behind it.

  • As a set is an unordered collection, so the order of elements in the resulting new set may not match the order in the source iterable.
  • Set comprehension is mainly focused on filtering and transforming elements, making it less suitable for complex scenarios requiring multiple steps.

Best Practices for using Set Comprehension


To make the most out of set comprehension, consider the following best practices:

  • Set comprehension works best for simple transformations and filtering. For complicated scenarios, try to use alternative approaches, like loops or functions to improve readability.
  • Remember that sets only contain unique elements. If your transformation or conditions do not guarantee uniqueness, you may end up with unexpected results.
  • Choose meaningful names for variables to enhance code readability and maintainability.
  • Write comments or docstring to explain the purpose and logic of your set comprehension, especially if you are performing complicated operations.
  • If the output expression within set comprehension becomes too long, split it into multiple lines with appropriate indentation and grouping to enhance clarity.

Scenarios for using Set Comprehension


We can apply set comprehension in various scenarios, including:

(a) Data cleaning: Filtering out duplicate or invalid entries from a data set.

(b) Data transformation: Applying mathematical or logical operations to elements in the set of data.

(c) Set operations: Computing the union, intersection, or difference of multiple sets.


Frequently Asked Questions

Q1: Is it possible to use set comprehension with other data types, such as dictionaries or strings?

A: Set comprehension is specifically designed to create sets. However, you can use dictionary comprehension or string comprehension, depending on your requirements.

Q2: Is the order of elements guaranteed in set comprehension?

A: No, sets are unordered collections, so the order of elements in the resulting set may not match the order in the source iterable.

Q3: Can we nest set comprehension within another set comprehension?

A: Yes, we can nest set comprehension within another set comprehension to create complex sets or perform multiple transformations.

Q4: How does set comprehension handle duplicates?

A: Set comprehension automatically removes duplicate elements, as sets only contain unique elements.


Set comprehension is a powerful technique or feature in Python that allows us to create sets using concise and expressive code. It helps to simplify data manipulation, filtering, and transformation.

By understanding the syntax, best practices, and limitations of set comprehension, you can use this feature effectively in your Python programs. Hope that you will have understood the basic points of set comprehension and practiced all example programs. In the next, we will understand about nested dictionary in Python will the help of some important examples.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love