Comprehensions in Python

Comprehensions in Python are a great way to provide the user with a precise and concise way of constructing fresh new sequences using pre-defined sequences like sets, lists, dictionaries, gensets, etc. Comprehensions in Python are mainly of four types: list comprehension, dictionary comprehension, set comprehension, and generator comprehension. Let us see how these types work along with their python codes. We will also talk about the nested comprehensions and if they are useful or not. Later we will discuss the benefits of list comprehensions along with the conditions when it is not suggested to opt for list comprehensions in Python.

Python Comprehension

Python Comprehensions have the ability to create an elegant way of creating new lists in python. They may contain or may not have an ‘if’ condition statement in them. Below is the syntax of list comprehension in python: 


Output_list[output_exp for var in input_list if (var satisfies the condition)


Let us see an example below where the user wants to create a list with output that contains only even numbers present in the input list. The technique to solve this is described in the python code below where the user will make the use of loops and list comprehension both.


in_list = [10, 20, 31, 47, 50, 69, 70, 70]


out_list = []


for var in in_list:

if var % 2 == 0:

out_list.append(var)


print("The output list using for loop will be:", out_list)




Output:

The output list using for loop will be: [10, 20, 50, 70, 70]

Now let us see an example below where the user wants to create a list with squares of all the numbers using loops and list comprehension. 

out_list = []

for var in range(1, 12):

out_list.append(var ** 2)

 

print("The output list using for loop will be:", out_list)


Output:

The output list using for loop will be: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121]

Become a Python Certified professional  by learning this HKR Python Training !

Types of Comprehensions in Python

They are 4 Tpes,

  • List Comprehensions,
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Comprehensions

List Comprehension:

List comprehensions in python are needed for creating a new list derived from an already existing list just by manipulating the elements. In other words, the user can create a new list by manipulating the values of a pre-existing list. List comprehensions usually have multiple nested for list comprehensions.

Let us see the example below where we have a list and then we create a new one by adding 2 to each element.


exist_list = [a for a in range(6)]

print(exist_list)


new_list = [var+2 for var in exist_list]


print(new_list)


Output:

[0, 1, 2, 3, 4, 5]

[2, 3, 4, 5, 6, 7]


A new list is created where the values inside the exist_list are manipulated. The conditions for the new_list always depend on the choice of the user.

Dictionary Comprehension:

 It holds a key-value pair in python. They are used to create a new dictionary from a set of existing dictionaries by manipulating the elements of the pre-existing one. The user can also take in a list and create a dictionary out of it.  It all depends on the user whether he wants to shorten the length of the dictionary or increase the values in it. 

Let us see the example below where we have a list and then we create a new dictionary from it by adding 2 to each element.

exist_list = [a for a in range(6)]

print(exist_list)


new_dict = {var:var + 2 for var in exist_list }


print(new_dict)


Output:

[0, 1, 2, 3, 4, 5]

{0: 2, 1: 3, 2: 4, 3: 5, 4: 6, 5: 7}

A new dictionary is created where the values inside the exist_list were manipulated. The conditions for the new_dict always depend on the choice of the user.

A user can also take in 2 lists and can create a new dictionary from it. Let us see the example below to execute this:

L1 = [a for a in range(6)]

L2 = ['Tue','Wed','Thu','Fri', 'Sat']

print(L1)

print(L2)

new_dict ={key:value for (key, value) in zip(L1, L2)}

print(new_dict)




Output:

[0, 1, 2, 3, 4, 5]

['Tue', 'Wed', 'Thu', 'Fri', 'Sat']

{0: 'Tue', 1: 'Wed', 2: 'Thu', 3: 'Fri', 4: 'Sat'}

  If you want to Explore more about Python? then read our updated article - Python Tutorial.

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Set Comprehension:

Set comprehensions are used to create a new set from a set of existing sets by manipulating the elements of the pre-existing one. The user can also take in a list and create a new set out of it.  It all depends on the user whether he wants to shorten the length of the set or increase the values in it. 

Let us see the example below where we have a list and then we create a new set from it by adding 2 to each element.

exist_set = {a for a in range(6)}

print(exist_set)


new_set = {var+2 for var in exist_set}


print(new_set)




Output:

{0, 1, 2, 3, 4, 5}

{2, 3, 4, 5, 6, 7}

A new list is created where the values inside the exist_list are manipulated. The conditions for the new_set always depend on the choice of the user.

Generator Comprehension:

Generator comprehensions can create new generators from a set of existing generators by manipulating the elements of the pre-existing one. These generators are well efficient with memory as they help to allocate the memory as the items get generated rather than allocating them at the beginning. The user can also take in a list and create a new generator out of it.  It all depends on the user whether he wants to shorten the length of the set or increase the values in it. 

Let us see the example below where we have a list and then we create a new set from it by adding 2 to each element.

exist_list = [a for a in range(6)]

print(exist_list)


new_set = (var+2 for var in exist_list)


for var1 in new_set:

   print(var1, end=" ")


Output:

{0, 1, 2, 3, 4, 5}

A new list is created where the values inside the exist_list are manipulated. The conditions for the new_set always depend on the choice of the user.

If you have any doubts on Python,then get them clarified from Python Industry experts on our Python Community

Subscribe to our youtube channel to get new updates..!

Nested Comprehensions in Python

Comprehensions in python can be present in nested form too which means one inside the other. They increase the code complexity though which is actually against the main fundamental of the comprehension in python. It aims at making the work lesser and manipulating the existing list in such a way that it satisfies the need of the user. Hence it is not advisable to use list comprehensions and they should be avoided as much as a user can. 

Let us see an example of nested comprehension in python:

matrix_1 = [[2,3,6], [2,3,6], [2,3,6]]


matrix_1 = []

k=0

for i in range(2):

   matrix_1.append([])     

   for j in range(2):

       matrix_1[i].append((j+1)*2)        

print(matrix_1)

   print(var1, end=" ")


Output:

[[2, 4], [2, 4]]

Benefits of Using List Comprehensions

  • A user is able to reduce a 3 line code into one line
  • The code designed with list comprehensions is easily recognizable and acknowledges instantly
  • The code created with list comprehension is fast as the memory is allocated to the list before adding values or elements to the list
  • The code with list comprehension fits well with python hence the code creation is pythonic making it very helpful for the user

When not to use List Comprehensions in Python

  • A user should not opt for list comprehensions when he doesn't actually want a list. The functions and methods won't actually return anything when used with list comprehensions so it would be meaningless
  • The logic becomes too long sometimes as the user sometimes packs too much information inside the single statement that it becomes harder. 

   Top 50 frequently asked Python interview Question and answers !

Python Training Certification

Weekday / Weekend Batches

Conclusion

In this article, we have talked about comprehension in python. Comprehensions in Python are mainly of four types: list comprehension, dictionary comprehension, set comprehension, and generator comprehension. We have discussed all these types along with their examples with python code. We have also elaborated on the advantages of list comprehension as well as when not to use list comprehension. Now we will be discussing some frequently asked questions by the developers and will give solutions for them.

Related Article

  1. Python Boolean
  2. List to String in Python
  3. Python Arrays
  4. Python Community
  5. Python Training in Pune

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 28th Mar 2023, Weekday batch

  • Batch starts on 1st Apr 2023, Weekend batch

  • Batch starts on 5th Apr 2023, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

Although List comprehension lets the user create lists easily. However, they occupy more memory during this process. They aren't really bad but inefficient sometimes.

List comprehensions are way faster than for loops in python

Comprehensions actually work as a single tool that a user can use in a lot of different situations depending on the need, making the user’s work more efficient and faster.

Protected by Astra Security