Enable Dark Mode!
comprehensions-in-python.jpg
By: Midhun Sankar

Comprehensions in Python

Technical

As we know, there are quite a few data types used in python. We mainly use comprehension in lists, dictionaries, and sets.
A comprehension is used like an operation on the data set (whether it is a list, dict, or set) that is generally a few lines of code and shrinks to a single or multiple lines, thereby increasing the readability and making the code compact.
Not only that, when we are referring to another developer's code, we need at least basic knowledge of what comprehensions are and how comprehensions work. So, let’s get on with it.
In this blog, we will be discussing comprehensions used in python.
There is mainly four types of comprehension in python:
List Comprehension
Dictionary Comprehension
Set Comprehension
Generator Comprehension

List Comprehension

List comprehension is a faster and more compact way of creating a new list from an existing list. List Comprehension is generally faster than usual operations are done using loops and functions.
The basic syntax for list comprehension is:
output_list = [expression for variable in input_list if (condition)]
Suppose there’s a list, and we want to create a new list from the existing list containing even numbers. Without comprehension, we write,
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = []
for x in list:
if x % 2 == 0:
    even_list.append(x)
    print(even_list)
We get the output [2, 4, 6, 8, 10]
By using comprehension, we can shrink the code.
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]?even_list = [x for x in list if x % 2 == 0]?print(even_list)
We get the same output. That is, [2, 4, 6, 8, 10]
This, by using comprehensions, we can shrink the code and decrease the number of loops and improve readability and make it compact.
Same as the list, we can use comprehension for dictionaries also.

Dictionary Comprehension

Same as list comprehension, we use dictionary comprehension to create a new dictionary from the list. Using comprehension in a dictionary, we can shrink the code and improve its readability and make it compact. Before getting into dictionary comprehension, we should first keep in mind the basic structure and features of the dictionary. That is, the dictionary is mapped using key, value pairs.
The basic syntax of dictionary comprehension is:
output_dictionary = {key:value for (key, value) in list if (condition)}
Suppose we want to create a dictionary that contains the square of the key as a value. Without 
comprehension, we write,
key_list = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10]?output_dictionary = {}?for key in key_list:?output_dictionary[key] = key**2?print(output_dictionary)
The output would be {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
By using comprehension, we can shrink the code.
key_list = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10]?output_dictionary = {key: key**2 for key in key_list}?print(output_dictionary)
We get the same output. That is, {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
The four lines of code that we generally write to create a dictionary, using comprehension, we can shrink to just two lines of code.
We can also use conditions, if any, with comprehension.
Let’s construct a dictionary with even numbers in the list as key and their squares as values.
key_list = [1, 2, 3, 4, 5, 6 ,7, 8, 9, 10]?output_dictionary = { key: key**2 for key in key_list if key % 2 == 0}?print(output_dictionary)
The output would be {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Next, we’ll talk about set comprehensions.

Set Comprehension

Set comprehensions are similar to list comprehension. The main difference between a list and a set is unordered and it doesn’t allow duplicate elements compared to sets that allow duplicate elements. Sets are denoted by curly braces {}.
The basic syntax of set comprehension is:
output_set = {expression for variable in input_list if (condition)}
Let’s check an example for set comprehension.
Suppose we want to create a set eliminating the duplicate values in the list.
set_list = ['A', 'S', 'P', 'A', 'R', 'A', 'G', 'U', 'S']?output_set = set()?for element in set_list:?output_set.add(element)?print(output_set)
The output would be {'S', 'G', 'R', 'P', 'A', 'U'}
By using comprehension, we can shrink the code to:
set_list = ['A', 'S', 'P', 'A', 'R', 'A', 'G', 'U', 'S']?output_set = {element for element in set_list}?print(output_set)
Here also, we’ll get the same output, {'S', 'G', 'R', 'P', 'A', 'U'}
Like mentioned in the above comprehension, we can use conditions in set comprehension also. For that, we add the condition at the end of the code.

Generator Comprehension

Generator comprehensions are similar to list comprehensions but they use circular brackets. They are much more efficient compared to list comprehensions as they allocate memory for each value, rather than allocating memory for the whole list.
The basic syntax of generator comprehension is:
output_generator = (expression for variable in input_list if (condition))
Let’s check an example of Generator comprehension. Here we are creating a generator of even numbers from the input list.
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]?output_generator = (var for var in input_list if var % 2 == 0)?print(output_generator)?print(type(output_generator))
When we print the output generator, we get a temporary value, and when we print the type, we get the class ‘generator’ as output.
To see the value of output_generator, we must convert it to a tuple.
Now, we get the output as (2, 4, 6, 8, 10), and the type ‘tuple’.
That’s it about the basic python comprehensions. It is quite easy to understand and helps to make the code very compact. Feel free to comment in case of any queries.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 
whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

London

Cybrosys Limited
Alpha House,
100 Borough High Street, London,
SE1 1LB, United Kingdom

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message