Advance Python - Comprehensions

avatar

NaN years ago

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

  1. Faster then for-loop
  2. Reduce the code
  3. Easy to implement


Disadvantages of comprehension in python

  1. Difficult to understand if the logic is too long
  2. Hader to debug errors if the logic is complex


Use resources to learn more about comprehension and its type.

approvedApproved by experts
Advance Topics

Neuton's Mission

We are a team of young and enthusiastic people who are passionate about education and want to help students to learn the skills they need to succeed in life. If you want to support us, please join our community.

phonephonephonephonemail