In order to be more “pythonic” while writing python code, many best practices are recommended. Python set comprehensions, like “dictionary comprehension” or “list comprehension” or using “warlus operator(introduced in python 3.8 )” is found in use in many python libraries.
How to write
new_set = { expression(i) for i in old_list if condition(i) }
The above expression shows the way a python set comprehension is written. Note that the the right hand side of the “=” starts with “{” and ends with “}” . This means that whatever we write inside the curly braces, it generates a new set, which is the output for the python set comprehension . Also the generated set does not contain any duplicates. Which is natural with the set data type in python.
Let’s see an example for the same. Here we shall be creating a set of items ( squared by it’s original value -> i*i ) if the value of the item ( i ) is even (i %2 == 0 )
new_set = { i*i for i in old_list if i%2 ==0 }In the above code our expression is i*i and condition is i%2 == 0. For more details let’s look at the github repository for the code. lets take a look at the below function.
def set_comp(): old_list = [0, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9] new_set = {i * i for i in old_list if i % 2 == 0} return new_setif we execute the below line of code
print(set_comp())Then we will get the below output
{0, 64, 4, 36, 16}here the old list has two duplicate item-> “2”. But if we run the function, the output will not be having the duplicate value 4 as the output has python datatype “set” .
When to use set comprehension ?
When we want to achieve the below points we should consider using a list comprehension in python-
-
- create a new set from a computation
- create a set using a declarative approach
- we want to apply some filters while creating the set
-
Benefits of using set comprehension
-
-
- As it is a declarative way of creating a new set while using set comprehension, the code becomes more readable.
- By using set comprehension we can avoid using loops and map() , and therefore not care about initializing a new set before the start of the loop or not care about the order of augments passed inside the map() . And thus we are better off in writing code
- Set comprehension also enables us to write code by applying filter-logic to wipe out data that are not important
-