In this tutorial, you will learn about comprehension. Comprehension in Python provides a short and concise way to create a sequence (such as a list, dictionary, set, etc). Python support four types of comprehension which are a list, set, dictionary, and Generators Comprehension.
Before going through this Comprehension in Python article, please read the following articles.
Headings of Contents
What are Python Comprehensions?
Python comprehension provides a short and concise way to create a sequence like a list, dictionary, set and generator, etc. This is one of the most important concepts to create any sequence like a list, dictionary, set, or generator because it takes less time in comparison to traditional ways.
Python support 4 types of comprehension.
- List Comprehension
- Set Comprehension
- Dictionary Comprehension
- Generator Comprehension
Let’s understand all the Python comprehension one by one along with examples.
List Comprehension:
List comprehension provides a concise way to create a new list. list comprehension use square bracket ( [ ] ).
Syntax of List Comprehension
output_list = [expression for var in list]
Example: Creating a new one with another list using list comprehension
Here, I have an already defined list called old_list having some integer items and now I am about to create a new list using the list comprehension concept.
Suppose we want to create an output list that contains only the even number from 1 to 10 using another list. Then we have two ways to create an output list first is using Python for loop and the other is using list comprehension.
- Create a new list without list comprehension
old_list = [1,2,3,4,5,6,7,8,9,10]
new_list = []
for var in old_list:
if var % 2 == 0:
new_list.append(var)
print("Output list without list comprehension: ",new_list)
Output
Output list without list comprehension: [2, 4, 6, 8, 10]
2. Create a new list using list comprehension
old_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = [var for var in old_list if var % 2 == 0]
print("Output list using list comprehension: ", new_list)
Output
Output list using list comprehension: [2, 4, 6, 8, 10]
Dictionary Comprehension
Dictionary comprehension looks like list comprehension. Dictionary comprehension provides a facility to create a new dictionary. Dictionary comprehension using an inside curly bracket ( { } ).
A dictionary comprehension takes the form {key: value for (key, value) in iterable}.
Syntax of Dictionary Comprehension:
output_variable = {key: value for (key, value) in iterable}
Example: Creating Dictionary using dictionary comprehension
Suppose we want to create a new dictionary that contains squares of numbers who exactly divisible by 3 between 1 to 20.
- Create a new dictionary without dictionary comprehension.
old_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
new_dict = {}
for var in old_list:
if var % 3 == 0:
new_dict[var] = var * var
print("New dictionary without dictionary comprehension: ",new_dict)
Output
New dictionary without dictionary comprehension: {3: 9, 6: 36, 9: 81, 12: 144, 15: 225, 18: 324}
2. Create a new dictionary without dictionary comprehension.
old_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
new_dict = {var: var * var for var in old_list if var % 3 == 0}
print("New Dictionary using dictionary comprehension:- ", new_dict)
Output
New Dictionary using dictionary comprehension:- {3: 9, 6: 36, 9: 81, 12: 144, 15: 225, 18: 324}
you can check the type of the new dictionary using the type() function.
print(type(new_dict))
Set comprehension:
set comprehension is the same as a list comprehension. The only difference between list comprehension and set comprehension is, list comprehension uses a square bracket ( [ ] )but set comprehension uses a curly bracket ( { } ).
Syntax of set comprehension
output_variable = {expression for var in list}
Example: Creating a set using set comprehension
Here, In this example section. I have a students_name set having some student names included. Now, I am about to create a new set that will contain only student names starting with ‘Vi‘. I will create a new set using both ways, using set comprehension and without using set comprehension.
- create a new set without set comprehension.
students_name = {"Vishvajit", "Vikas", "Vinod", "Akash", "Veronika", "Vaibhav", "John","Shashank"}
output_set = set()
for i in students_name:
if i.startswith("Vi"):
output_set.add(i)
print("Students whose name starts with 'Vi' :- ", output_set)
Output
Students whose name starts with 'Vi' :- {'Vishvajit', 'Vikas', 'Vinod'}
You can check the data type of new_set using the type() function.
a = type(new_set)
print(a)
2. create a new set using set comprehension.
students_name = {"Vishvajit", "Vikas", "Vinod", "Akash", "Veronika", "Vaibhav", "John","Shashank"}
new_set = {i for i in students_name if i.startswith("Vi")}
print("Students whose name starts with 'Vi' :- ", new_set)
Output
Students whose name starts with 'Vi' :- {'Vinod', 'Vishvajit', 'Vikas'}
Generator Comprehension:
Generator Comprehension is very similar to list comprehension. One difference between them is that generator comprehensions use circular brackets ( ( ) ) whereas list comprehensions use square brackets ( [ ] ). You have to keep one thing in mind, It always returns a generator object. To see the items of the generator object, you will have to convert them into the list, set, etc.
I have a student_names set having some names of students included, Now I am going to create a generator object that will contain only those student names which do not start with ‘Vi‘.
Example: Creating generator comprehension
students_name = {"Vishvajit", "Vikas", "Vinod", "Akash", "Veronika", "Vaibhav", "John","Shashank"}
generator_object = (i for i in students_name if not i.startswith("Vi"))
print("Generator Object :- ", generator_object)
Output
Generator Object :- <generator object <genexpr> at 0x0000022A109099A0>
As you can see in the above output, how the generator object is looking where we are not able to see the items of the generator object.
Example: Converting generator object to the list
To convert any generator object to a list, use the list() function.
print(list(generator_object))
# Output:- ['Veronika', 'Shashank', 'Vaibhav', 'Akash', 'John']
Example: Converting generator object to set
The set() function will be used to convert the generator object to the set. As you can see below.
print(set(generator_object))
# Output:- {'Akash', 'Veronika', 'Shashank', 'John', 'Vaibhav'}
Note:- Order of items will be different, when you will convert generator object to set because set is unordered.
Example: Using for loop with generator object
Even, to access the items of the generator object, Python for loop can be used. Let see.
for i in generator_object:
print(i)
Output
John
Shashank
Akash
Veronika
Vaibhav
Conclusion
In this article, you have seen approx all about Comprehension in Python. Python Comprehension is one the best way to create a list, set, Dictionary, and Generator comprehension in just one line. Python comprehension is a little faster than ways to create a list, set, and dictionary using the traditional way.
I will highly recommend you, Always use Python comprehension, when you have a requirement to create a list, set, or dictionary in just a few lines of code.
If you like this Comprehension tutorial, please share and keep visiting for further Python tutorials.
For more information:- Click Here
Thanks for your valuable time … 🙏🙏❤️❤️