Python Set Comprehension


A Python set is an unordered collection of unique items that is iterable, mutable, and has no duplicate items. You can perform mathematical set operations such as union, intersection, set difference, etc on Python sets.

The set comprehension is similar to the Python list or dictionary comprehension it provides a shorter syntax to create sets in Python. In this article, you will learn Python list comprehension and its usage.

Syntax of Python set comprehension

You can create a set in python using set comprehension in the given way –

set_var= {x for x in iterable}

Where set_var is a set variable, item x will get added to set_var every time for loop iterate over iterable. Some examples of creating sets are given ahead in this article.

Example of Python set using set comprehension

In our example, we will create a set that will contain integers from 1 to 10. First, we will see the usual way in which a Python set is created and then we will create the same set using set comprehension.

num=set()
for x in range(1,11):
        num.add(x)
print(num)

Using set comprehension

Using set comprehension you can reduce the number of lines of code. You can write the same code as given below –

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

you can see the output in the given image –

Using conditional statements in set comprehension

You can use conditional statements in set comprehension to modify the output on the basis of a condition. We will understand this with the help of an example.

Now suppose we want a set of even numbers between 1 and 11. For this, we need to apply a condition to find the even numbers and add them to the set of even numbers.

The given code will create a set of even numbers between 1 and 11 using set comprehension.

even_num={x for x in range(1,11) if x%2==0}
print(even_num)

You can see the output in the given image –

Nested set comprehension

Using a set inside another is called a nested set. You can’t use a set inside another set that means the nesting of the set is not possible instead you can do this by using the inner set as frozenset.

Now see the given example –

var_num={frozenset([i,j]) for j in range(4,7) for i in range(6,8)}
print(var_num)

You can see the output in the given image –

Conclusion

This is how you can use set comprehension to write shorter codes. Now If you have any query then write us in the comments below.

Leave a Comment