Skip to content

List , Dict and Set Python Comprehensions

python comprehension

Python comprehension gives us shorter syntax to create a list , set and dictionary from an iterator .

List Comprehension in Python

List comprehension in Python gives us shorter syntax to create a list from an iterator .

Syntax of List Comprehension in Python

new_list =[expression for item in iterable [if conditional]]

OR

new_list =[expression [if conditional] for item in iterable ]

Why to use List Comprehension in Python?

Suppose we have a list of some numbers. Now we need to create a new list with numbers divisible by 3 from the given list. The general program for this is –

list_of_no=[2,7,4,9,11,6]
new_list=[]
for number in list_of_no:
    if(number%3==0):
        new_list.append(number)
         
print(new_list)
[9, 6]

In the above code first an empty list has been created . Then each item in the old list is checked to see if it is divisible by 3. Those that are divisible by 3 are added to the new list.

We can solve this problem using list comprehension also –

list_of_no=[2,7,4,9,11,6]
#using list comprehension
new_list=[number for number in list_of_no if number%3==0]
print(new_list)
[9, 6]
  • In the above code the previous problem has been solved with the help of list comprehension.
  • Here list comprehension has three parts, they are –number (1), for number in list_of_no (2), if number% 3 == 0 (3) .
  • By for number in list_of_no (2) each number in the old list has been iterated, the iterated numbers have been checked by if number% 3 == 0 (3). Numbers that return True have been added to the new list as number (1).

Now we will see how list comprehension solve the problem with the help of a table –

numberfor number in list_of_noif number%3==0
22%3==0(false)
77%3==0(false)
44%3==0(false)
999%3==0(true)
1111%3==0(false)
666%3==0(true)

So we can easily see that program can be written in very few lines using list comprehension. This is why list comprehension is used.

List Comprehension in Python with if-else

Suppose, from the aforesaid list, we want to make a list so that the number divisible by 2 is replaced by even and the number not divisible by 2 is replaced by odd, then the program will be.-

list_of_no=[2,7,4,9,11,6]
new_list=["even" if number%2==0 else "odd" for number in list_of_no]
print(new_list)
['even', 'odd', 'even', 'odd', 'odd', 'even']

In the above code each of the numbers in the given list is checked to see if it is divisible by 2. If it is divisible by 2 then it is replaced by even else it is replaced by odd. The program is presented in the form of a table for ease of understanding –

“even” if number%2==0 else “odd”for number in list_of_noif number%2==0
“even”22%2==0(true)
“odd”77%2==0(false)
“even”44%2==0(true)
“odd”99%2==0(false)
“odd”1111%2==0(false)
“even”66%2==0(true)

Replace map function with List Comprehension in Python to take multiple integer input in a single line

We can easily solve the problem of receiving multiple integer inputs on the same line through map() function –

To learn about map() function click here

print(list(map(int,input().split())))
2 5 4 8
[2, 5, 4, 8]

In the above code if we enter “2 5 4 8” as input and it will print [2, 5, 4, 8].

Now we will solve this problem through list comprehension –

print([int(number) for number in input().split()])
2 5 4 8
[2, 5, 4, 8]

In the above code if we enter "2 5 4 8" as input . input().Split() will convert it to ["2", "5", "4", "8"]. The rest is shown through a table for ease of understanding –

int(number)for number in input().split()
2“2”
5“5”
4“4”
8“8”

Replace filter function with List Comprehension in Python

Suppose we have a list of names. Now we need to create a new list so that there will be names from old list that are 6 or less in length. We can easily solve this problem with the help of filter() function –

To learn about filter() function click here

list_of_name=["sourav","sudipta","partha","joy","gurudas","arup"]
print(list(filter(lambda x:len(x)<=6,list_of_name)))
['sourav', 'partha', 'joy', 'arup']

In the above code, filter() function will check each name of list_of_name whether its length is 6 or less, if it is 6 or less then filter() function will add the name to the new list .

Now we will solve this problem through list comprehension –

list_of_name=["sourav","sudipta","partha","joy","gurudas","arup"]
print([name for name in list_of_name if len(name)<=6])
['sourav', 'partha', 'joy', 'arup']

In the above code, each name of list_of_name is checked whether its length is 6 or less, if the length is 6 or less then it will be in the new list else it will be omitted.

Set Comprehension in Python

Set comprehension in Python gives us shorter syntax to create a set from an iterator .

Syntax of Set Comprehension in Python

new_set ={expression for item in iterable [if conditional]}

OR

new_set ={expression [if conditional] for item in iterable }

Set Comprehension in Python Examples

Example 1: Set comprehension in Python with if condition

list_of_name=["sourav","sudipta","partha","joy","gurudas","arup"]
#using set comprehension
print({name for name in list_of_name if len(name)<=6})
{'arup', 'sourav', 'partha', 'joy'}

The above code is the solution to the previous problem which we have solved through set comprehension with if condition.

Example 2: Set comprehension in Python with if else

list_of_name=["sourav","sudipta","partha","joy","gurudas","arup"]
# using set comprehension
# if length<=6 then yes otherwise no
print({"yes" if len(name)<=6 else "no" for name in list_of_name})
{'yes', 'no'}

In the above code we have used set comprehension with if else . As set does not allow duplicate values so only 1 “yes” and 1 “no” is seen in the output .

Dictionary Comprehension in Python

Dictionary comprehension in Python gives us shorter syntax to create a dictionary from an iterator .

Syntax of Dictionary Comprehension in Python

new_dictionary ={key:value for item in iterable [if conditional]}

OR

new_dictionary ={key:(value1 [if conditional] value2) for item in iterable }

Dictionary Comprehension in Python Examples

Example 1: Dictionary comprehension in Python with if condition

list_of_name=["sourav","sudipta","partha","joy","gurudas","arup"]
# using dict comprehension with if condition
print({name:len(name) for name in list_of_name if len(name)<=6})
{'sourav': 6, 'partha': 6, 'joy': 3, 'arup': 4}

We have created a dictionary by dictionary comprehension with if condition taking name as “key” and len(name) as “value” –

Example 2 : Dictionary comprehension in Python with if else

list_of_name=["sourav","sudipta","partha","joy","gurudas","arup"]
# using dict comprehension with if else
print({name:("yes" if len(name)<=6 else "no") for name in list_of_name })
{'sourav': 'yes', 'sudipta': 'no', 'partha': 'yes', 'joy': 'yes', 'gurudas': 'no', 'arup': 'yes'}

In the above code we have used dictionary comprehension in python with if else .

Nested Python Comprehension

With nested comprehension python we can easily create list of list, dictionary of list, list of dictionary, list of set etc.

Suppose a school has five classes and each class has ten students, now the correct data structure for storing the results of all of them is a dictionary contains a list –

Nested Comprehension Python Examples

list_of_class=["class-v","class-vi","class-vii","class-viii","class-ix"]
#dictionary comprehension nested by list comprehension
print({class_name:["roll"+str(number) for number in range(1,11)] for class_name in list_of_class})
{'class-v': ['roll1', 'roll2', 'roll3', 'roll4', 'roll5', 'roll6', 'roll7', 'roll8', 'roll9', 'roll10'], 'class-vi': ['roll1', 'roll2', 'roll3', 'roll4', 'roll5', 'roll6', 'roll7', 'roll8', 'roll9', 'roll10'], 'class-vii': ['roll1', 'roll2', 'roll3', 'roll4', 'roll5', 'roll6', 'roll7', 'roll8', 'roll9', 'roll10'], 'class-viii': ['roll1', 'roll2', 'roll3', 'roll4', 'roll5', 'roll6', 'roll7', 'roll8', 'roll9', 'roll10'], 'class-ix': ['roll1', 'roll2', 'roll3', 'roll4', 'roll5', 'roll6', 'roll7', 'roll8', 'roll9', 'roll10']}

In the above code, a dictionary has been created by taking the name of each class as key and the list of roll number of ten students of each class as value.

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply