Member-only story
List and dictionary comprehensions in Python
In this tutorial, we will learn about list and dictionary comprehensions in Python. We will begin with list comprehension and then we discuss dictionary comprehension.
List Comprehension
List comprehension is an elegant way of creating a new list from an existing list. Let us understand Python’s list comprehension using examples.
Example 1:
At first, we create dummy data. It is a list L of the first ten natural numbers. Using list comprehension, we create another list E which contains the even numbers from L.
L = [1,2,3,4,5,6,7,8,9,10] # dummy dataE = [num for num in L if num%2 == 0]print(E)
The output of the above print function is shown below:
[2, 4, 6, 8, 10]
In the above example, we have given a list L. From this list L, we have created another list E consisting of only the even numbers which are present in the list L. The same task can be done using a loop also. The corresponding codes are shown below:
L = [1,2,3,4,5,6,7,8,9,10] # dummy dataE = [] # empty listfor num in L:
if num%2 == 0:
E.append(num)