AppDividend
Latest Code Tutorials

Python Set Comprehension: The Complete Guide

0

Sets in Python are used to store multiple elements in a single element. A set is a collection that is both unordered and unindexed. Sets can be defined in curly braces.

When it comes to comprehension, list comprehension is the most used technique to create a list in Python, and also there is dictionary comprehension, which is less popular. Still, there is also set comprehension, which we will see in this article.

Python Set Comprehension

Set comprehension in Python is an elegant way to define and create sets based on existing sets, lists, or dictionaries. The key perspective of set comprehension that makes it different is that it returns a set, which means the items inside the set will be unordered and cannot contain duplicates.

Syntax

{expression(variable) for variable in input_set [predicate][, …]}

Parameters

expression

It is an optional argument, an output expression creating members of the new set from members of the input set that meet the predicate expression criteria.

variable

It is a required parameter that is a variable representing members of an input set.

input_set

It is a required argument that represents the input set.

predicate

It is an optional parameter that serves as a filter on members of the input set.

[, …]]

It is an optional argument that is another nested comprehension.

Example

simpsons = "Homer Simpson is son of Abraham Simpson and Father of Bart Simpson"
chars = simpsons.split()
simpsons_set = {word for word in chars}
print(simpsons_set)

Output

{'son', 'Bart', 'is', 'Abraham', 'Father', 'Simpson', 'of', 'Homer', 'and'}

In this example, we have first defined a string and then used the string split() function that splits the string into the list. Then used the set comprehension to create a set from list items.

If you notice, then you can see that the initial order of the words as they appeared in the sentence was not kept in the result. If you run this program, again and again, then you will find different output every time.

Adding conditions within Set Comprehension

You can add custom conditions while using set comprehension to create a set. Let’s say we want only words whose length is >= 4. Less than 4 will be filtered out. To do that, we can use a comparison operator.

simpsons = "Homer Simpson is son of Abraham Simpson and Father of Bart Simpson"
chars = simpsons.split()
simpsons_set = {word for word in chars if len(word) >= 4}
print(simpsons_set)

Output

{'Bart', 'Simpson', 'Abraham', 'Father', 'Homer'}

You can see that output contains only words whose string length is equal to or greater than 4.

In Python, sets inside sets, called the inner sets, have to be frozen sets, or you will get an error.

A frozen set is just like a set, although sets are mutable and frozen sets are not. 

In other words, sets are changeable, which makes them unhashable, and therefore they cannot exist as items within a larger set unless they are frozen. Luckily, we can simply make sets into frozen sets by enclosing them in the frozenset() function.

simpsons = "Homer Simpson is son of Abraham Simpson and Father of Bart Simpson"
chars = simpsons.split()
vowels = ['a', 'e', 'i', 'o', 'u']
constants = {frozenset(
    {letter for letter in word if letter not in vowels}) for word in chars}
print(constants)

Output

{frozenset({'s'}), frozenset({'s', 'n'}), 
 frozenset({'H', 'm', 'r'}), 
 frozenset({'f'}), 
 frozenset({'d', 'n'}), 
 frozenset({'t', 'h', 'r', 'F'}), 
 frozenset({'S', 's', 'n', 'p', 'm'}), 
 frozenset({'r', 'h', 'b', 'm', 'A'}), 
 frozenset({'B', 't', 'r'})}

Please remember that the frozenset() will be required when we are dealing with sets within sets. Sets within lists or dictionaries do not require frozen sets.

Conclusion

Set comprehension is a more compact and faster way to create sets in Python. You should avoid very long set comprehensions in one line to assure that code is user-friendly. You can use for loop to replace the set comprehension code each time, but you can’t replace for loop code with a set comprehension every time.

That is it for the Set Comprehension example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.