1. Home
  2. Docs
  3. Python 201
  4. Comprehensions

Comprehensions

 
In this lesson you will learn about comprehensions.

In Python we have different type of comprehensions, But let’s start

with the most popular one List comprehension.

 

List Comprehension

 

Before we look at list comprehension, Lets build a list of numbers using a range().

The expected list is num_list = [0,1,2,3,4,5,6,7,8,9]

 

num_list = []

for num in range(10):

    num_list.append(num)
    
num_list

output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  

To get num_list we have three lines of code.

Now let’s look at another way of doing it. By using list comprehensions.

  

num_list = [num for num in range(10)]

num_list

output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  

That’s just one line, [num for num in range(10)] creates the list.

 
List comprehension is, simple a way of creating a list using a for-loop.
 
syntax :
 

[expr for item in iterabe [filter condition]]

  

How to construct list comprehensions

its simple, first you write for loop

Step 1:

for item in iterable

Step 2:

then put item expr before for loop

expr for item in iterable

Step 3:

then put filter condition at the end of for loop,

Step 4:

filter condition is optional,

expr for item in iterabe filter condition

Step 5:

then enclose whole line in [ ] square brackets.

[ expr for item in iterable]

Now let’s look at some list comprehension examples.

 

Using an expression in list comprehension

Ex 1:
 
Get multiples of 2.
  

multiples_of_two = [i * 2 for i in range(1,10)]

multiples_of_two

output:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

  
Notice the first part, [i * 2, we are using an expression here.
 

Using function in list comprehension

 
You can also use function, to process item to get the desired output.

Suppose we have list of strings, and want to get length of each string.
 
Ex 2:
  

['Stairway to Heaven','Whole Lotta Love','Black Dog','Rock and Roll']

We can use built-in function len() and get a list of lengths.

songs = ['Stairway to Heaven','Whole Lotta Love','Black Dog','Rock and Roll']

len_songs = [len(song) for song in songs]

len_songs


output:

[18, 16, 9, 13]

  
Ex 3:
 

Using user defined function in list comprehension

  

def get_initials(full_name):

    f,l = full_name.split()

    return f[0] + l[0]

  
get_initials() returns first letter from first and last name.

employees = [“James Lamb”, “Martin Hogg”,”Mary Woods”]

initials = [get_initials(name) for name in employees]

initials

output:

[‘JL’, ‘MH’, ‘MW’]

  

Using conditionals in List comprehension

 
Ex 4:

Get only numbers divisible by 3 between 40 and 60.

  

odd_40_to_60 = [num for num in range(40,60) if num %3 == 0]

odd_40_to_60

output:

[42, 45, 48, 51, 54, 57]

  

notice the last part after for loop, if num %3 == 0,

We can apply conditions on the output generated.

Ex 5:

Another example showing usage of user defined function to filter output.
Function returns True if a given number is divisible by both 2 and 3.

  

def check_cond(num):

    if num % 2 == 0 and num % 3 == 0:

        return True
    
    
proc_nums = [num for num in range(1,30) if check_cond(num)]

proc_nums

output:

[6, 12, 18, 24]

  

Multiple for loops iteration

 
Sometimes you want generate list from multiple iterables.

To do this we have add another for loop, its like nested for loops.
 
Ex 6:
  

list1 = ['x', 'y']

list2 = [0,1]

to_gether = [(m,n) for m in list1 for n in list2]


to_gether


output:

[('x', 0), ('x', 1), ('y', 0), ('y', 1)]


or same example to generate co-ordinate values.

list1 = [0,1]

list2 = [0,1]

to_gether = [(m,n) for m in list1 for n in list2]

to_gether


output:

[(0, 0), (0, 1), (1, 0), (1, 1)]

  

Ex 7:

T-shirts with color and sizes.

  

colors = ['Royal Blue', 'Grey']

sizes = ['S','M','L','XL']

tshirts = [(color, size) for color in colors for size in sizes]

print(tshirts)

output:

[('Royal Blue', 'S'),
 ('Royal Blue', 'M'),
 ('Royal Blue', 'L'),
 ('Royal Blue', 'XL'),
 ('Grey', 'S'),
 ('Grey', 'M'),
 ('Grey', 'L'),
 ('Grey', 'XL')]

  

Note you can extend this type construct for three, four or any number of iterations,

but it’s strongly advised, not use more than two for loops inside a list comprehension.

As with number of loops, the readability suffers.

And also its not advised have,

complex conditional filtering inside list comprehensions.

Look at the below example.
  

[x if x % 2 else -x for x in range(15) if x % 3]


  
can you guess the output:
  

output:

[1, -2, -4, 5, 7, -8, -10, 11, 13, -14]

  
Even though condition is simple, when you use comprehension,

it looks complicated.

More comprehensions

Once you understand the list comprehensions,

other comprehensions like set, dictionary comprehensions

or generator expression,are straight forward.

The syntax is almost same only the braces change.

let’s have a look at them.
 

Set comprehension

Set comprehensions, use { } curly braces, instead of [ ]

{expr for var in interable [filter condition]}

Ex 1 :

See the difference between list and set comprehension.

list comprehension
  


[a % 3 for a in range(20)]

output:

[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1]

  
set comprehension
  

{a % 3 for a in range(20)}

output:

{0, 1, 2}

  
Recall, set() don’t contain duplicate elements.

 

Dictionary comprehension

 
similar to set comprehension but with little change in syntax.

here a ( : ) colon used to assign key to a value.

  

{key: expr for var in interable [filter condition]}

  

Ex 1:

  

{n:2 * n for n in range(5)}

output:

{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

  
Ex 2:

Creating a list, using built-in str() and assigning values.

  

{str(n):n ** 2 for n in range(5)}

output:

{'0': 0, '1': 1, '2': 4, '3': 9, '4': 16}

  
Ex 3:

Creating dict with keys from list, and assigning an index as value.

  

menus = ['file','edit','view','exit']

{k:v for v,k in enumerate(menus)}

output:

{'edit': 1, 'exit': 3, 'file': 0, 'view': 2}

  

Ex 4:
 
One common use of dictionary comprehension is transposing.

Transpose is to interchange keys and values.

  

# dictionary with key-value pairs

menus = {'file':0,'edit':1,'view':2,'exit':3 }

# keys assigned with value, and value with key
 
{k:v for v,k in menus.items()}

output:

{0: 'file', 1: 'edit', 2: 'view', 3: 'exit'}

  

When not use

 
Don’t use comprehensions
 
1. for deeply nested iteration, as readability suffers
 
2. If code is complex and better understood using simple for-loop