List Comprehensions provides easy and functional way to create list in python. We could make a single line of code which otherwise would take a few lines. list comprehension always returns a result list.

Here is a example. Let say we want to pick a set of numbers in a list if they are between num > 3 and num < 9 range.

new_numbers_list = []
for num in range(1,11):
    if num > 3 and num < 9:
        new_numbers_list.append(num)

print(new_numbers_list) #>>> [4, 5, 6, 7, 8]

This same code can be written in a single line of code in list comprehension. (Well 1 line, excluding the print)

new_numbers_list_com = [num for num in range(1,11) if num > 3 and num < 9]
print(new_numbers_list_com) #>>> [4, 5, 6, 7, 8]

Execute on the python commandline.

┌─[Zubair AHMED][AHMEDZBYR-WRK-HORSE][/d/python]
└─▪ python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # same as range(1,11)
>>> [num * 2 for num in numbers if num > 3 and num < 9]
[8, 10, 12, 14, 16]
>>>
>>>
>>> d = {"CA": "Canada", "GB": "Great Britain", "IN": "India"}
>>> [ id for id in d ]
['CA', 'GB', 'IN']
>>>
>>> [ id.lower() for id in d ] 
['ca', 'gb', 'in']
>>>
>>> [ id.lower() for id in d ] 
['ca', 'gb', 'in']
>>>
>>> [ v.lower() for k,v in d.items() if k == 'GB']  
['great britain']
>>>
>>> [ v.upper() for k,v in d.items() if k == 'IN']        
['INDIA']

What is a list comprehension

[expression for item in iterable if condition == True]
[num * 2 for num in numbers if num > 3 and num < 9] #>>> [8, 10, 12, 14, 16]

Syntax

[expression for item in iterable if condition == True]
  • First part in [ and end ] is the new list to be created.
  • expression - new element in the list.
    • we can perform more operation in the expression for the newly select element/item for our new list.
    • example: num * 2 will multiple 2 to every new item in the new list.
  • for item in iterable we are looping an existing iterable.
    • iterable is any object which we can iterate over.
  • condition - condition expression on which the new elements to be selected.
    • we are selecting elements which match the expression num > 3 and num < 9.

Example 1.

┌─[Zubair AHMED][AHMEDZBYR-WRK-HORSE][/d/python]
└─▪ python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> motorcycles = ['yamaha', 'ducati', 'kawasaki', 'ktm']
>>> [moto for moto in motorcycles if moto != 'ktm' ]      
['yamaha', 'ducati', 'kawasaki']
>>>
>>> [num for num in range(1,10)]  # Without the if condition, range is a build-in function
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> [num if num < 7 else 8 for num in range(1,10)]  # if the number is < 7 continue, else will be replaced by 8.
[1, 2, 3, 4, 5, 6, 8, 8, 8]

Example 2. List comprehension with 2 arrays.

┌─[Zubair AHMED][AHMEDZBYR-WRK-HORSE][/d/python]
└─▪ python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import string
>>> list(string.ascii_lowercase)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> arr1 = list(string.ascii_lowercase)
>>> arr2 = [ 'c', 'a', 'x', 'i']
>>> [ a1 for a1 in arr1 for a2 in arr2 if a1 == a2]    
['a', 'c', 'i', 'x']
>>>

In the above example we have 2 lists arr1 and arr2

#[ /--\    /------------\  /------------\   /--------\ ] 
 [  a1     for a1 in arr1  for a2 in arr2   if a1 == a2] 
  • a1 our new array.
  • a1 for a1 in arr1 - traversing the first list.
  • for a2 in arr2 - traversing second list (note that we dont have a2 here, we use this list to compare both)
  • if a1 == a2 - condition for new list a1

Example 3. We can continue on with multiple lists.

┌─[Zubair AHMED][AHMEDZBYR-WRK-HORSE][/d/python]
└─▪ python
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import string
>>> list(string.ascii_lowercase)   # This will give us all the alphabets in lower case. 
>>> arr1 = list(string.ascii_lowercase)
>>> arr2 = [ 'c', 'a', 'x', 'i']
>>> arr3 = [ 'c' ] 
>>> [ a1 for a1 in arr1 for a2 in arr2 for a3 in arr3 if a1 == a2 and a1 == a3] 
['c']

This is again similar to 2 lists.

#[ /--\    /------------\  /------------\   /------------\    /---------------------\ ] 
 [  a1     for a1 in arr1  for a2 in arr2   for a3 in arr3    if a1 == a2 and a1 == a3] 

Example 4. Adding 2 lists.

Cartesian product, think of these as a matrix, every element in x is added to the y list. we get a 3 x 3 elements in the new list.

>>> [x+y for x in [10,30,50] for y in [20,40,60]] # Cartesian product, think of these as a matrix, every element in x is added to the y list. we get a 3 x 3 elements in the new list.   
[30, 50, 70, 50, 70, 90, 70, 90, 110]