To know the importance of Comprehension in Python, first we have to understand what is Comprehension?
List Comprehension
List Comprehension is defined as an elegant way to define, create a list in Python and consists of brackets that contains an expression followed by for clause. It is efficient in both computationally and in terms of coding space and time.
Syntax :- The list comprehension starts with '[' and ']'.
[ expression for item in list if conditional ]
Let's learn it with the help examples
Example 1:
Suppose you have generate a list of square over a range of values
first ,you will try to do it with using for loop
Using For Loop
>>> lst = []
>>> for i in range(1,11):
... lst.append(i**2)
...
>>> lst
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
do this way will definately do the job but, here we can make use of list comprehension to make this a one liner, let's see
Using List comprehension
>>> lst = [i**2 for i in range(1,11)]
>>> lst
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
in the above , the left most expression will be evaluated and store in the list for every value in the for loop
Conditionals in List Comprehension
We can also add conditional statements to the list comprehension.
to store values in the list based wheather the condition is True or False, We can create a list using range(), operators, etc.
let's understand this with an example.
Syntax: newlist = [expression for item in iterable if condition == True]
Example 2:
Suppose there are students in a class and you have to filter the student names based on the performance in the exam, you have a dict of students with key as there name and value as there marks
So, if a student get marks greater than or equal to 40 then he/she will be included in the list else he/she will not be included.
First we will try to do it with for loop, then
using list comprehension
Using For loop
>>> students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}
>>> selected_students = []
>>> for student,marks in students.items():
... if marks >= 40:
... selected_students.append(student)
...
>>> selected_students
['ram', 'harry', 'john', 'seta', 'philip']
>>>
Using List comprehension
>>> students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}
>>> selected_students = [student for student,marks in students.items() if marks >= 40]
>>> selected_students
['ram', 'harry', 'john', 'seta', 'philip']
With the help of list comprehension we have achived the same task with the same Ridability
Nested List Comprehensions
Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. let's understand it with an example.
Example 3:-
Suppose you have to generate a matrix where each row contain value from 1 to 4, we will try to do it using for loop then using nestd list comprehensions
Using For loop
>>> for i in range(3):
...
... # Append an empty sublist inside the list
... matrix.append([])
...
... for j in range(5):
... matrix[i].append(j)
...
>>> matrix
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Using Nested List Comprehensions
>>> matrix = [[i for i in range(5)] for _ in range(3)]
>>> matrix
[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Dictionary Comprehension
Just like we use list comprehension ,in the similar way we can also create dictionary in one or two line instead of writing extra line . we use { , } instead of [ , ] braces,
all the other syntax is similar.
let's understand with the example
Example 4:-
you have given a lits of fruits and list list of calories corresponding to each of the fruits , now you have to generate a dict of fruits with
key as name of the fruit
value as it calories it has
Using For loop
>>>
>>> fruits = ["apple","pineapple","banana","orange","papaya","strawberry","grapes","watermalon"]
>>> calories = [100,141,65,43,120,80,110,200]
>>> fruit_dict = {}
>>> for i in range(len(fruits)):
... fruit_dict[fruits[i]] = calories[i]
...
>>> fruit_dict
{'apple': 100, 'pineapple': 141, 'banana': 65, 'orange': 43, 'papaya': 120, 'strawberry': 80, 'grapes': 110, 'watermalon': 200}
Using Dict Comprehension
>>> fruits = ["apple","pineapple","banana","orange","papaya","strawberry","grapes","watermalon"]
>>> calories = [100,141,65,43,120,80,110,200]
>>> fruits_dict = { fruits[i]:calories[i] for i in range(len(fruits))}
>>> fruits_dict
{'apple': 100, 'pineapple': 141, 'banana': 65, 'orange': 43, 'papaya': 120, 'strawberry': 80, 'grapes': 110, 'watermalon': 200}
Use can also Use Condtional Statement in Dict Comprehension as we used in List Comprehension
let's take small example
Example 5 :-
We will added a student name and his marks based on wheather he/she has got marks greater than or equal to 40 , Refer to example 4.
Using For loop
>>> students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}
>>> selected_students_dict = {}
>>> for student,marks in students.items():
... if marks >= 40:
... selected_students_dict[student] = marks
...
>>> selected_students_dict
{'ram': 44, 'harry': 75, 'john': 54, 'seta': 65, 'philip': 56}
Using Dict Comprehension
>>> students = {'ram':44,'shyam':22,'harry':75,'john':54,'robert':25,'seta':65,'max':23,'harry':75,'robin':24,'philip':56}
>>> selected_students_dict = {student:marks for student,marks in students.items() if marks >= 40}
>>> selected_students_dict
{'ram': 44, 'harry': 75, 'john': 54, 'seta': 65, 'philip': 56}
Now we have come to an end , the above examples will be enough for you to started with list comprehension , after all it one of the most powerful features of python that every pythonista must now,
i'm added some key takeways below. All the best for your future python explorations :-)
Key Takeawys
-> List comprehension is an elegant way to define and create lists based on existing lists.
-> List comprehension is generally more compact and faster than normal functions and loops for creating list.
-> we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.
-> every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.
Top comments (0)