Comprehension in Python

what are comprehensions in python ?

Python Comprehension provide us short and construct sequences and will helps to reduce the code and increase the execution speed of the scripts and the python supports four types of comprehension:

Comprehensive Python Cheatsheet click to view.

1) List Comprehension
2) Dictionary Comprehension
3) Set Comprehension
4) Generator Comprehension

Syntax : [ expr(item) for item in iterable ]

1) List Comprehension in Python :

When you want to create new list containing the square of each item exist in list. Let see how to do this with for loop and list comprehension and which method is better for.

a) Comprehension with for loop :

listdata=[]
for i in range(10):
    listdata.append(i*i)

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

b) Comprehension without loop :

listdata = [i*i for i in range(10)]
print(listdata)

I think you see the difference b/w comprehension with loop or without loop.

c) Python Comprehension If Else: :

Here we use if condition in python list comprehension create a output list which contains only the numbers is divided by 2.

lis = [i for i in range(11) if i % 2 == 0] 
print(lis)

#[0, 2, 4, 6, 8, 10]

d) Python lambda in list comprehensions :

Here is simple example write a function to check number is greater than 5. and lambda is very useful when you dealing with functions and lambda is anonymous function.

check_num = lambda x: 'Num greater than 5' if x > 5 else 'Num not greater than 5'
print(check_num(10))

#Num greater than 5

e) Python comprehension with map :

map() function takes two arguments function and iterables because map passes each item in iterable through a function and return all elements having passed through function and function applied on each element present in iterables.

numlist = [2,3,4,5,6]
increased = list(map(lambda x: x+3 , numlist))
print(increased)

#[5, 6, 7, 8, 9]

my_list = [0,1,2,3,4,5,6]
print(map(lambda x: x+1,my_list))

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

f) Comprehension with filter :

Python comprehension filter with lambda the function same as map() but the difference in filter the filter out the elements from which not under the condition in this example find number is comes under the condition like show numbers is greater than 2 and less than 5.

my_list = [0,1,2,3,4,5,6]
print(filter(lambda x: x>2 and x<5,my_list))

# [3,4]

g) Ccomprehension with reduce :

from functools import reduce
items = [1,2,3,4,5]
sum_all = reduce(lambda x,y: x + y, items)

# 15

items = [1, 24, 17, 14, 9, 32, 2]
all_max = reduce(lambda a,b: a if (a > b) else b, items)
 
print (all_max) # 32

2) Dictionary Comprehension:

Extend the concept of python comprehensions we also create a dictionary using dictionary comprehensions.

syntax : { key_expr:value_expr for item in iterable }

Some dict comprehension examples:

1)
dictdata = {i:i**i for i in range(1, 5)}
print(dictdata)

# {1: 1, 2: 4, 3: 27, 4: 256}

2) 
input_list = [1,2,3,4,5,6,7] 
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0} 
# {1: 1, 3: 27, 5: 125, 7: 343}

3)
old_price = {'price1': 1.02, 'price2': 2.5, 'price': 2.5}
condition_price = 0.76
new_price = {item: value*condition_price for (item, value) in old_price.items()}
print(new_price)

# {'price2': 1.9, 'price1': 0.7752, 'price': 1.9}

4)
original_dict = {'jack': 38, 'michael': 48, 'guido': 57, 'john': 33}
even_dict = {k: v for (k, v) in original_dict.items() if v % 2 == 0}
print(even_dict) 

# {'michael': 48, 'jack': 38}

3) Set Comprehension in Python:

The set comprehension is same as list comprehension but in set comprehension use {} brackets.

syntax : { expr(item) for item in iterable }

Set comprehension examples:

set_gen={i+1 for i in range(20)}
set_gen={(i,j) for j in range(4,7) for i in range(6,8)}
print(set_gen)

#set([(6, 4), (6, 6), (7, 6), (7, 4), (7, 5), (6, 5)])

my_set = {char for char in "hello"}
print(my_set)
#set(['h', 'e', 'l', 'o'])

num_100 = {num for num in range(1, 101)}
print(num_100)
# set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100])

input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7] 
set_using_comp = {var for var in input_list if var % 2 == 0}
print(set_using_comp)
#set([2, 4, 6])

4) Generator Comprehensions in python:

Generator comprehension is same as list comprehensions but generator comprehension creating a list and keeping the sequences in the memory. the normal function return a statement but generator return a generator object.

Generator Comprehensions examples:

list_comprehension = [i for i in range(11) if i % 2 == 0] 
print(list_comprehension) 
output: 0 2 4 6 8 10 

generator_expression = (i for i in range(11) if i % 2 == 0) 
print(generator_expression) 
output: <generator object  at 0x000001452B1EEC50>

if you want to print the output of the generator expressions.we can iterate the whole object like:
for i in generator_expression: 
    print(i)

#output
0
2
4
6
8
10

If you like the article share with your friends and you have any question or query related to article and any suggestions please leave in comment box.

Thanks for reading the Article.

Leave a Reply

Your email address will not be published. Required fields are marked *