Comprehensions are syntactic constructs that enable sequences to be built from other sequences in a clear and concise manner. Here, we will cover list comprehensions and dictionary comprehensions.
Using list comprehensions is much more concise and elegant than explicit for loops. An example of creating a list using a loop is as follows:
L1 = [10,20,30,24,18] L2 = [8,14,15,20,10] L3=[] for i in range(len(L1)): L3.append(L1[i]-L2[i]) L3
You know this code from our earlier discussions. The same code using a list comprehension is as follows:
# using list comprehension L1 = [10,20,30,24,18] L2 = [8,14,15,20,10] L3 = [L1[i]-L2[i] for i in range(0,len(L1))] L3
You can see that in the square brackets, you need to first put in the operation/output that you desire, followed by the loops from top to bottom. In the next video, you will learn how dictionary comprehensions work.
Let’s look at an example to understand the dictionary comprehension better. First, using the traditional approach, let’s create a dictionary that has the first ten even natural numbers as keys and the square of each number as the value to the key.
# Creating a dictionary consisting of even natural numbers as key and square of each element as value ordinary_dict ={} for i in range(2,21): if i%2==0: ordinary_dict[i]= i**2 ordinary_dict
The same code in terms of a dictionary comprehension is as follows:
#Using dictionary comprehension updated_dict = {i:i**2 for i in range(2,21 ) if i%2 ==0} updated_dict
You can see that the comprehension is inside curly brackets, representing that it is dictionary comprehension. The expression inside the brackets first starts with the operation/output that you desire, and then loops and conditionals occur in the same order of the regular code.