How to use List Comprehensions in Python

Keyur Paralkar
3 min readSep 15, 2017

--

Set is a collection of things or to be more precise it is a set of numbers. Usually sets are represented in different forms for example Set builder form, Roaster form etc. Normally sets are represented in the following manner

X = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
Y = {0, 2, 4, 6, 8, 10}

And the same sets X and Y can be represented in set builder form as follows

X = {x^2 : x in (0...9)}
Y = {y : y is even}

The above sets can be represented by List comprehension in python. It is a very simple concept which is used to implement the sets. The value returned by list comprehension is nothing but a List. The above example of sets can be implemented in python as

>>> X = [x*x for x in range(0,10)]
>>> X
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> Y = [y for y in range(10) if(y%2==0)]
>>> Y
[0, 2, 4, 6, 8]

In the statement i.e [x*x for x in range(0,10)] x in for loop acts as an iterating variable which iterates from 0 to 10 and each value of x is returned to outer value of x that is (x*x) and then each computed value of x*x is stored in the list. Let’s go through each iteration to visualise this list comprehension.

Passes         x       x*x       X       []1              0       0*0       0       [0]
2 1 1*1 1 [0,1]
3 2 2*2 4 [0,1,4]
4 3 3*3 9 [0,1,4,9]
5 4 4*4 16 [0,1,4,9,16]
6 5 5*5 25 [0,1,4,9,16,25]
7 6 6*6 36 [0,1,4,9,16,25,36]
8 7 7*7 49 [0,1,4,9,16,25,36,49]
9 8 8*8 64 [0,1,4,9,16,25,36,49,64]
10 9 9*9 81 [0,1,4,9,16,25,36,49,64,81]

Note: In the above example range(m,n) function generates a list of numbers — -from m to n-1 (excluding n). Similar to range() function there is xrange() function which returns an object which represents sequence of number in the range. xrange() is much faster as compared to range().

Second example [y for y in range(10) if(y%2==0)] is very similar to the first example, just the difference is that every number in iterating variable is checked for the condition if(y%2==0) i.e if the number is even or odd. According to this condition each number is returned to the outer variable y which in turn is appended in the list. Generally list comprehensions are

some_variable = [ iter_var/_do_something for iter_var in range(n) (..condition..)] 

Note: iter_var is the iterating variable and _do_something can be any function which does not perform any operation to the console like print statement etc.

Note: In list comprehensions print operation is not allowed as it would interrupt the execution of list comprehension.

>>> m = [print("*") for x in range(1,25)]
File "<stdin>", line 1
m = [print("*") for x in range(1,25)]
^
SyntaxError: invalid syntax

In list comprehensions nested for loop can also be implemented. Consider an example where we need to find out similar elements of two list and store it in another list. Let those two lists be m, n and x be the list where we need to store the result.

>>> m = [10, 19, 15, 8, 11, 8, 29, 18, 14, 7, 5, 22, 9, 28, 21, 23]
>>> n = [27, 29, 21, 3, 16, 11, 11, 6, 7, 8, 14, 27, 19, 29, 15, 26]
>>> x = [j for i in m for j in n if(i==j)]
>>> x
[19, 15, 8, 11, 11, 8, 29, 29, 14, 7, 21]

In the above list comprehension each in m is compared with each in n element and if they are similar then they are stored into the list. List comprehensions are not only applicable to numbers but they also work with strings. Consider this example where we store each word of the sentence “Lorem Ipsum is simply dummy text of the printing and typesetting industry.” into a list called listOfWords using split() function.

listOfWords = "Lorem Ipsum is simply dummy text of the printing and typesetting industry".split()
>>> listOfWords
['Lorem', 'Ipsum', 'is', 'simply', 'dummy', 'text', 'of', 'the', 'printing', 'and', 'typesetting', 'industry']

Our goal is to find length of each word in the sentence. Then the length of each word can be calculated as follows

>>> wordLength = [len(j) for j in listOfWords]
>>> wordLength
[5, 5, 2, 6, 5, 4, 2, 3, 8, 3, 11, 8]

List comprehensions are difficult to understand when there are nested for loops. They are more compact and faster as compared to explicit for loops.

If you Liked this article, please share or press ❤ below.

--

--