Comprehension in Python is a concept that offers shorter syntax to create a new sequence based on the value of an existing sequence with or without condition. There are 4 types of comprehension in Python:
- List Comprehension
- Set Comprehension
- Dictionary Comprehension
- Generator Comprehension
List Comprehension provides a faster way to create new lists. The following is the basic structure of a list comprehension:
newlist = [expression for item in iterable if condition == True]
Set comprehension is pretty similar to list comprehension except it uses curly brackets { }. Let’s look at the following example to understand set comprehensions:
// creating set that contain numbers only divisible by 2 old_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] new_set = {var for var in input_list if var % 2 == 0}
Dictionary Comprehension is an extension of set comprehension, we can also create a dictionary using dictionary comprehensions. The basic structure of dictionary comprehension looks like this:
newdict = {key:value for (key, value) in iterable if condition = true}
Generator comprehension is pretty similar to list comprehension except it uses circular brackets ( ). Let’s look at the following example to understand generator comprehension:
// creating generator that contain numbers only divisible by 2 old_list = [1, 2, 3, 4, 4, 5, 6, 7, 7] new_gen = (var for var in input_list if var % 2 == 0)
Advantages of comprehension in python
- Faster then for-loop
- Reduce the code
- Easy to implement
Disadvantages of comprehension in python
- Difficult to understand if the logic is too long
- Hader to debug errors if the logic is complex
Use resources to learn more about comprehension and its type.