Home » Set Comprehension in Python

# Set Comprehension in Python

In this tutorial let’s learn about Set Comprehension in Python. Sets are used in Python to store multiple elements in a single element. A collection that is both unordered and unindexed is referred to as a set. Curly brackets can be used to define sets.

When it comes to comprehension, list comprehension is the most commonly used technique for creating a list in Python followed by dictionary comprehension, which is less commonly used.

Contents

## What is set comprehension in Python?

Set comprehension is a Python approach for generating sets from elements of other iterables such as lists, sets, or tuples. Set comprehension is like list comprehension which can be used instead of a for loop to construct a new set and add elements to it.

#### Syntax for set comprehension in Python

new_set= { expression for element in  iterable }

Explanation :

The iterable in Python can be any iterable object or data structure from which we must use the elements to form the new set.
The element denotes the iterable element that must be included in the set.
Any mathematical expression generated from the element can be used as the expression.
The name of the new set that must be formed from the elements of the iterable is new_set.

Code Example :

``````sample_list = [1, 2, 3, 4, 5]
print("List:",sample_list)

new_set = {element*2 for element in sample_list}

print("The Created Set is:",new_set)``````

Output :

List: [1, 2, 3, 4, 5]
The Created Set is: {2, 4, 6, 8, 10}

## Adding conditions within Set Comprehension

When creating a set with set comprehension, you can include custom criteria or mathematical expressions. Assume we only want words with a length greater than four. That is words length Less than four will be discarded. We may accomplish this by use a comparison operator as shown below.

Code Example :

``````sample_string = 'Sets are used in Python to store multiple elements'
print("String :",sample_string)

words = sample_string.split()
new_set = {word for word in words if len(word) >= 4}

print(" Set :",new_set)``````

Output :

String : Sets are used in Python to store multiple elements
Set : {‘store’, ‘Sets’, ‘elements’, ‘Python’, ‘used’, ‘multiple’}

## Nested Set Comprehension in Python

Nested Sets are the Sets within sets, known as inner sets in Python must be frozen sets or an error will occur.

A frozen set is similar to a set, except that sets are mutable while frozen sets are not. In other words, because sets are changeable, they are unhashable, and they cannot exist as items within a larger set unless they are frozen. Fortunately, we can easily convert sets to frozen sets by enclosing them in the frozenset() function.

Code Example :

``````sample_string = 'Sets are used in Python to store multiple elements'

words = sample_string.split()
vowels = ['a', 'e', 'i', 'o', 'u']
new_set = {frozenset(
{letter for letter in word if letter not in vowels}) for word in words}

print(" Set :",new_set)``````

Output :

Set : {
frozenset({‘s’, ‘d’}),
frozenset({‘t’, ‘m’, ‘l’, ‘n’, ‘s’}),
frozenset({‘m’, ‘p’, ‘t’, ‘l’}),
frozenset({‘n’}),
frozenset({‘t’}),
frozenset({‘r’}), frozenset({‘t’, ‘r’, ‘s’}),
frozenset({‘t’, ‘P’, ‘y’, ‘h’, ‘n’}),
frozenset({‘t’, ‘s’, ‘S’})}

## Create a set from elements of another set using Set Comprehension in Python

If you need to create a set out of elements from another set, you can do it by creating a simple set. After you’ve created a new set, you can add elements to it with the add() method and for loop. But we can also do the same with set Comprehension in python without using add() method.

In the following example, we made a new set from an old set by multiplying each element with 2.

Code Example :

``````sample_set = {1, 2, 3, 4, 5}
print('Initial set :',sample_set)

new_set = {element*2 for element in sample_list}

print("The Created set is :",new_set)``````

Output :

Initial set : {1, 2, 3, 4, 5}
The Created set is : {2, 4, 6, 8, 10}

## Filter elements from a set based on a condition using Set Comprehension

By applying specific conditions to the elements of an old set, we can construct a new set from the elements of the old set. You may accomplish this with a for loop by utilizing a conditional statement and the add() method. Instead of using a for loop and add() method, you can use set comprehension to filter out elements from an old set to build a new set, as shown below.

Code Example :

``````sample_set = {1, 2, 3, 4, 5}
print('Initial set :',sample_set)

new_set = {element for element in sample_list if element % 2 != 0}

print("The Created set is :",new_set)``````

Output :

Initial set : {1, 2, 3, 4, 5}
The Created set is : {1, 3, 5}

## Change the data type of elements of the set

Set comprehension can also be used to modify the data types of set elements, as seen in the following example. In this case, we changed all of the integer elements of a set to strings.

Code Example :

``````sample_set = {1, 2, 3, 4, 5}
print('Initial set :',sample_set)

new_set = {str(element) for element in sample_list }

print("The Created set is :",new_set)``````

Output :

Initial set : {1, 2, 3, 4, 5}
The Created set is : {‘3’, ‘5’, ‘2’, ‘4’, ‘1’}

## Conclusion

In Python, set comprehension is a more compact and faster technique to generate sets. To ensure that your code is user-friendly, avoid using very long set comprehensions on a single line. You can use the for loop to replace the set comprehension code each time, but you can’t replace the for loop code with a set comprehension each time.

Similar Posts: