Learn Python Programming

Python Comprehension


Comprehensions provide a very compact and shorter syntax to create a new sequence using an existing sequence. Comprehension usually have a single statement and perform the task.

  • List Comprehension
  • Set Comprehension
  • Dictionary Comprehension

List Comprehension

List comprehension is a creation of new list from the values of existing iterables list.

Syntax: new_list = [<expression> for item in iterable_object <if statement>]

Let us understand with an example: Suppose there is a list of fruits.

fruits = ["apple", "banana", "mango", "guava", "papaya", "kiwi", "cherry"]

In order to check, how many fruits name consist of ‘a’ alphabet in their name. For this we need to parse through a loop, and so a ‘For’ loop is required with one condition check for ‘a’ is available or not in each value of list. But using list comprehension we can achieve it in single line.

Using For Loop

fruits = ["apple", "banana", "mango", "guava", "papaya", "kiwi", "cherry"]
new_fruits_list = []

for x in fruits:
  if "a" in x:
    new_fruits_list .append(x)

print(new_fruits_list )

#Output
['apple', 'banana', 'mango', 'guava', 'papaya']

Using List Comprehension

fruits = ["apple", "banana", "mango", "guava", "papaya", "kiwi", "cherry"]
new_fruits_list = [x for x in fruits if 'a' in x]
print(new_fruits_list )

#Output
['apple', 'banana', 'mango', 'guava', 'papaya']

Example : Create a list of squares from 1 to 10.

squares = []
for i in range(1,11):
        squares.append(i**2)
print(squares)

#Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


#using list comprehension
squares = [i**2 for i in range(1,11)]
print(squares)

#Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Set Comprehension

Set comprehension represents a creation of new set from the values of existing iterables set.

Syntax: new_set = [<expression> for item in iterable_object <if statement>]

Let us understand with an example: Suppose there is a set of fruits.

fruits = {“apple”, “banana”, “mango”, “guava”, “papaya”, “kiwi”, “cherry”}
We will check the alphabet ‘a’ presence in each fruit name.

fruits = {"apple", "banana", "mango", "guava", "papaya", "kiwi", "cherry"}
new_fruits_set = {x for x in fruits if 'a' in x}
print(new_fruits_set)

#Output
{'banana', 'guava', 'mango', 'papaya', 'apple'}

Dictionary Comprehension

Dictionary comprehension is an compact and concise way of creating a new dictionary from and iterable object.

For example: A python program to calculate square of 1 to 10.

#normal program
square_dict = dict()
for num in range(1, 11):
    square_dict[num] = num**2
print(square_dict)

#Ouput
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Using dictionary comprehension:

#dictionary comprehension
square_dict = {num:num**2 for num in range(1,11)}
print(square_dict)

#Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}